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
.
Solution1:
Compare characters from top to bottom on the same column (same character index of the strings) before moving on to the next column.
code
/*
Time complexity : O(S), where S is the sum of all characters in all strings.
Space complexity : O(1). We only used constant extra space.
*/
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) { // 除str[0]外的一个String被扫完了
return strs[0].substring(0, i);
}
}
}
// 有可能strs[0]扫完了都没碰到垂直方向不相同的字符
return strs[0];
}
}