- Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
方法:从开始依次比较
思路:
选一个one_str作为参照,对其他strs都按位与one_str比较,直到出界或不相等
Time Complexity: O(n*min(k)) n个str,长度为k
Space Complexity: O(1)
Solution Code:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String one_str = strs[0]; // as reference
int max_length = 0;
// compare all strs with one_str char by char
for(int pos = 0; pos < one_str.length(); pos++) {
for(int i = 1; i < strs.length; i++) {
if(pos >= strs[i].length() || strs[i].charAt(pos) != one_str.charAt(pos))
{
return one_str.substring(0, max_length);
}
}
max_length++;
}
return one_str.substring(0, max_length);
}
}
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) {
return "";
}
String pre = strs[0];
int i = 1;
while(i < strs.length) {
while(strs[i].indexOf(pre) != 0) {
pre = pre.substring(0, pre.length() - 1);
}
i++;
}
return pre;
}
}
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0 || strs[0].length() == 0) return "";
int i = 0;
while(true) {
if(i >= strs[0].length()) return strs[0].substring(0, i);
Character c = strs[0].charAt(i);
for(String str: strs) {
if(i >= str.length() || str.charAt(i) != c) {
return strs[0].substring(0, i);
}
}
i++;
}
}
}