string.erase没掌握好,悲了个剧,2次过
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 string pre = ""; 7 if (!strs.size()) return pre; 8 for (int i = 0; i < strs[0].size(); i++) { 9 pre += strs[0][i]; 10 int j = 1; 11 for (; j < strs.size(); j++) { 12 if (pre != strs[j].substr(0, i+1)) break; 13 } 14 if (j != strs.size()) { 15 pre.erase(pre.size()-1, 1); 16 return pre; 17 } 18 } 19 return pre; 20 } 21 };
后来写了个更加精简的代码
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 sort(strs.begin(), strs.end()); 7 string ret; 8 if (!strs.size() || !strs[0].size()) return ret; 9 int cur = 0; 10 while (cur < strs[0].size() && strs[0][cur] == strs[strs.size()-1][cur]) { 11 ret += strs[0][cur]; 12 cur++; 13 } 14 return ret; 15 } 16 };
C#
1 public class Solution { 2 public string LongestCommonPrefix(string[] strs) { 3 Array.Sort(strs); 4 string ans = ""; 5 if (strs.Length == 0 || strs[0].Length == 0) return ans; 6 int cur = 0; 7 while (cur < strs[0].Length && strs[0][cur] == strs[strs.Length-1][cur]) { 8 ans += strs[0][cur]; 9 cur++; 10 } 11 return ans; 12 } 13 }