LeetCode 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
实现思路:
题目要求寻找一组字符串的最长公共前缀,方法就是双重循环,以第一个字符串为起始字符串,然后逐个对比,就是暴力法,其他方法的话之后可以再进行扩充。
AC代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0) return "";
string prefix=strs[0];//用初始做前缀
for(int i=0; i<strs.size(); i++) {
string key=strs[i],temp;
for(int j=0; j<key.length()&&j<prefix.length(); j++) {
if(key[j]==prefix[j]) temp+=key[j];
else break;
}
prefix=temp;
}
if(prefix.length()==0) return "";
else return prefix;
}
};