參考:《one-day-one-leetcode》
需要求出多個字串的最長前置詞字元串,即求出最小的字串,然後求出最小字串的長度和對應的字串,然後在最短字串的長度內進行和其他字串的匹配即可。
#include <iostream>#include <string>#include <vector>using namespace std;string longestCommonfix(vector<string>& strs){ int i = 0, min_len = strs[i].length(); string min_str = strs[i]; string s = ""; ++i; while (i < strs.size()){ if (min_len > strs[i].length()){ min_len = strs[i].length(); min_str = strs[i]; } i++; } bool flag = false; int j = 0; while (j < min_len){ int count_j = 0; for (int i = 0; i < strs.size(); i++){ if (strs[i][j] == min_str[j]){ count_j++; } else{ flag = true; break; } } if (flag == true) break; if (count_j == strs.size()) s += min_str[j]; j++; } return s;}int main(){ string s[] = { "abc", "abcw", "abcab", "abc" }; vector<string> v; for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++){ v.push_back(s[i]); } cout << longestCommonfix(v) << endl; return 0;}
運行結果: