[LeetCode]14.Longest Common Prefix
Write a function to find the longestcommon prefix string amongst an array of strings.
中文意思是:找出所有字符串的公共前缀,题目难度为easy。
思路:2个字符串的公共前缀,其长度肯定不会超过最短的字符串长度,设最短的字符串长度为n,那么只要比较这2个字符串的前n个字符即可。得出两个字符串的最长公共前缀prefix后,再用prefix作为新的字符串和字符数组中的下一个字符串比较,方法同上。
但是如果数组中的某个字符串长度为0,或者求得的当前公共前缀的长度为0,就直接返回空字符串。
//LeetCode_Longest Common Prefix class Solution { public: string longestCommonPrefix(vector<string> &strs) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (strs.size() == 0) return ""; string prefix = strs[0]; for (int i = 1; i < strs.size(); ++i) { if (prefix.length() == 0 || strs[i].length() == 0) return ""; int len = prefix.length() < strs[i].length() ? prefix.length() : strs[i].length(); int j; for (j = 0; j < len; ++j) { if (prefix[j] != strs[i][j]) break; } prefix = prefix.substr(0,j); } return prefix; } };