思想:利用C++ string::find 函数的特性,暴力匹配
重要特性:substr(start , [length ]) ;如果 length 为 0 或负数,将返回一个空字符串
string::find(str); //匹配返回首下标,不匹配返回string::nopos=-1
# include<iostream> # include<vector> # include<string> # include<algorithm> # include<math.h> # include<climits> # include<stack> # include<queue> using namespace std; string longestCommonPrefix(vector<string>& strs) { string res = strs.empty() ? "" : strs[0]; int n = strs.size(); for (int i = 1; i < n; i++) { while (strs[i].find(res) !=0)res = res.substr(0, res.size() - 1); // substr(start , [length ]) ;如果 length 为 0 或负数,将返回一个空字符串 } return res; } int main(void) { vector<string>s; s.push_back("abcdei"); s.push_back("abcdef"); s.push_back("abcdesadaa"); s.push_back("abcdesss"); cout << longestCommonPrefix(s) << endl; system("pause"); return 0; }