Problem
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
.
Solution (Java)
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length < 1) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String temp = strs[0];
int i = 1;
String cur;
while (temp.length() > 0 && i < strs.length) {
if (temp.length() > strs[i].length()) {
temp = temp.substring(0, strs[i].length());
}
cur = strs[i].substring(0, temp.length());
if (!cur.equals(temp)) {
temp = temp.substring(0, temp.length() - 1);
} else {
i++;
}
}
return temp;
}
}
Solution (Javascript)
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 0) return '';
var len1 = strs.length;
var len2 = strs[0].length;
var tmp = '';
var res = '';
outer: for (var i = 0; i < len2; i++) {
tmp = strs[0][i];
inner: for (var j = 1; j < len1; j++) {
if (strs[j][i] !== tmp) break outer;
}
res += tmp;
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n^2).
- Space complexity : O(1).