3.8—字符串—Longest Common Prefix

来源:互联网 发布:mac nice to meet you 编辑:程序博客网 时间:2024/06/10 04:39
描述
Write a function to find the longest common prefix string amongst an array of strings.

#include <iostream>#include <string>#include <vector>using namespace std;int MIN = 100000;string LongestCommonPrefix(vector<string> str){string res;for (int i = 0; i<str.size(); i++){if (str[i].size()<MIN)MIN = str[i].size();}for (int i = 0; i<MIN; i++){char temp = str[0][i];int j = 1;for (; j<str.size(); j++){if (temp != str[j][i])break;}if (j != str.size()){if (i == 0)return res;elsereturn str[0].substr(0, i);}}}int main(){vector<string> str;str.push_back("I am a man");str.push_back("I am a seuer");str.push_back("I am a Chinese");str.push_back("I am a good person");string res = LongestCommonPrefix(str);cout << res << endl;}

原创粉丝点击