C++
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string res;
if (strs.empty()) return res;
for (int i = 0; ; i++) {
if (i >= strs[0].size()) return res;
char c = strs[0][i];
for (auto& str: strs) {
if (str.size() <= i || str[i] != c) return res;
}
res += c;
}
return res;
}
};
Python3
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ""
for i in zip(*strs):
if len(set(i)) != 1:
return res
else:
res += i[0]
return res
Go
func longestCommonPrefix(strs []string) string {
res := ""
if len(strs) < 1 {
return res
}
for i := 0; ; i++ {
if i >= len(strs[0]) {
return res
}
c := strs[0][i]
for _, str := range strs {
if(i >= len(str) || c != str[i]) {
return res
}
}
res += string(c)
}
return res
}