Longest Common Prefix
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings. public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
StringBuilder sb = new StringBuilder();
int currLength = 0;
char currChar = '0';
while (true) {
if (strs[0].length() > currLength) {
currChar = strs[0].charAt(currLength);
} else return sb.toString();
for (String s : strs) {
if (s.length() <= currLength) return sb.toString();
if (s.charAt(currLength) != currChar) return sb.toString();
}
currLength++;
sb.append(currChar);
}
}
} class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) {
return "";
}
string prefix;
int curr_idx{0};
while (true) {
char curr_char{0};
for (const string& s : strs) {
if (s.size() == curr_idx) {
goto endLoop;
} else if (curr_char == 0) {
curr_char = s[curr_idx];
} else if (curr_char != s[curr_idx]) {
goto endLoop;
}
}
prefix += curr_char;
curr_idx++;
}
endLoop:
return prefix;
}
}; class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0: return ''
if len(strs) == 1: return strs[0]
strs.sort()
ret = ''
s1 = strs[0]
s2 = strs[-1]
i = 0
while True:
if len(s1) <= i or len(s2) <= i: return ret
if s1[i] == s2[i]:
ret += s1[i]
i += 1
else: return ret