leetCode 14. Longest Common Prefix 字符串
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
题目大意:求一组字符串的最长前缀。
代码如下:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.size() == 0) return ""; int minStrLen = strs[0].size(); string result; for(int i = 0 ;i < strs.size();i++) { if(strs[i].size() < minStrLen) { minStrLen = strs[i].size(); } } int i = 0; for( ; i < minStrLen;i++) { char a = strs[0][i]; int j = 0; for( ;j < strs.size();j++) { if(strs[j][i] != a) break; } if(j < strs.size()) break; } result = strs[0].substr(0,i); return result; } };
2016-08-10 17:44:00