完整代码如下:
#include#include #include using namespace std; string longestCommonPrefix(vector & strs){ int n = strs.size(); int m = strs[0].length(); string res = ""; char temp; bool flag = 1; for (int i = 1; i < n; i++) { if (strs[i].length() < m) m = strs[i].length(); } for (int i = 0; i < m; i++) { temp = strs[0][i]; for (int j = 0; j < n; j++) { if (strs[j][i] != temp) { flag = 0; break; } } if (flag == 1) res += temp; else break; } return res; } int main(){ vector vec; vec.push_back("flower"); vec.push_back("flow"); vec.push_back("flight"); for (int i = 0; i < vec.size(); ++i) { cout << vec[i] << endl; } cout << "the longestcommonprefix is:" << longestCommonPrefix(vec) << endl; vector vec2; vec2.push_back("dog"); vec2.push_back("racecar"); vec2.push_back("car"); for (int i = 0; i < vec2.size(); ++i) { cout << vec2[i] << endl; } cout << "the longestcommonprefix is:" << longestCommonPrefix(vec2) << endl; system("pause"); }



