Type:easy
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: ["flower","flow","flight"]Output:"fl"
Example 2:
Input: ["dog","racecar","car"]Output:""Explanation:There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
本题旨在查找一个vector<string>内所有字符串的最长公共前缀字符串,若没有则返回空。
设这个子串为cp,长度为cpc。遍历vector,从第一位开始依次比较每个字符串的前缀是否有strs[0][cpc]这个字符。当cpc大小大于某一字符串长度或某一字符串前缀与第一个字符串不相符,返回之前的cp。否则cpc增加,继续比较下一位。
注意本种解法在查找多个字符串公共最长前缀时,是挨个字符匹配的,不是整条子串去匹配的。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string cp = "";
for(int cpc = 0; strs.size() > 0 && cpc < strs[0].length(); cpc++){
for(int i = 0; i < strs.size() - 1; i++){
if(cpc >= strs[i+1].length() || strs[i][cpc] != strs[i+1][cpc] ) return cp;
}
cp = cp + strs[0][cpc];
}
return cp;
}
};