描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”
例子
思路
答案
- 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;
}
};