1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> #include <string> #include <vector> using namespace std;
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string result; if (strs.size() < 1) { return result; } result = strs[0]; for (int i = 1; i < strs.size(); ++i) { int index = 0; while (index < result.size() && index < strs[i].size()) { if (result[index] != strs[i][index]) { break; } index++; } result = result.substr(0, index); if (index == 0) return result; } return result; } };
int main() { vector<string> strs = {"flower", "flow", "flight"}; std::cout << Solution().longestCommonPrefix(strs) << std::endl; strs = {"dog", "racecar", "car"}; std::cout << Solution().longestCommonPrefix(strs) << std::endl; }
|