description
Write a function to find the longest common prefix string array.
If there is no common prefix, returns an empty string ""
Examples of
ideas
answer
- python
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs)==0: return ''
res = strs[0]
for i in range(len(res)):#长度是逐渐上涨的
for j in range(1,len(strs)):
# 如果同一位置字符不一样,或者此时长度超过该字符串
if i==len(strs[j]) or strs[j][i]!=res[i]:
return res[:i]
return res
- c++
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string res = strs[0];
for (int i=0; i<res.size(); i++)
for (int j=1; j<strs.size(); j++)
if (i==strs[j].size() || res[i]!=strs[j][i])
return res.substr(0,i);
return res;
}
};