[LeetCode] Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
模拟法,先选取第一个字符串,之后依次和后面的字符串得出LCP
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string> &strs) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (strs.size() == 0) 7 return ""; 8 9 string s = strs[0]; 10 11 for(int i = 1; i < strs.size(); i++) 12 { 13 int j = 0; 14 15 int len = min(strs[i].size(), s.size()); 16 17 while(j < len) 18 { 19 if (strs[i][j] != s[j]) 20 break; 21 j++; 22 } 23 24 s.erase(j, s.size()); 25 } 26 27 return s; 28 } 29 };