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
.
解题思路:从第一个字符开始,满足所有字符串该位置的字符相同,则结果加上该字符,否则返回已有的串长度。
C++
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans = "";
if(strs.size() == 0)
return ans;
if(strs.size() == 1)
return strs[0];
for(int i = 0; i < strs[0].length(); ++ i){
for(int j = 1; j < strs.size(); ++ j)
if(strs[0][i] != strs[j][i])
return ans;
ans += strs[0][i];
}
return ans;
}
};
Python
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
for i in range(len(strs[0])):
for j in range(1, len(strs)):
if i == len(strs[j]) or strs[0][i] != strs[j][i]:
return strs[0][:i]
return strs[0]