您的位置:首页 > 其它

找出一个字符串数组中最长公共前缀字符串

2016-12-10 19:14 405 查看
找出一个字符串数组中最长公共前缀字符串

1.水平扫描

public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++)
while (strs[i].indexOf(prefix) != 0) {                      \\返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
prefix = prefix.substring(0, prefix.length() - 1);      \\子字符串开始位置不为0则缩小子字符串,再进行对比
if (prefix.isEmpty()) return "";
}
return prefix;
}

Time complexity : O(S)O(S) ,
where S is the sum of all characters in all strings.

In the worst case all nn strings
are the same. The algorithm compares the string S1S1 with
the other strings [S_2
\ldots S_n][S​2​​…S​n​​] There
are SS character
comparisons, where S S is
the sum of all characters in the input array.
Space complexity : O(1)O(1).
We only used constant extra space.

2.垂直扫描
Imagine a very short string is at the end of the array. The above approach will still do SS comparisons. One way to optimize
this case is to do vertical scanning. We compare characters from top to bottom on the same column (same character index of the strings) before moving on to the next column.

public String longestCommonPrefix(String[] strs) {
if (strs == null || 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)
return strs[0].substring(0, i);
}
}
return strs[0];
}


Complexity Analysis
Time complexity : O(S)O(S) ,
where S is the sum of all characters in all strings. In the worst case there will be nn equal
strings with length mm and
the algorithm performs S
= m*nS=m∗n character
comparisons. Even though the worst case is still the same as Approach #1, in the best case there are at most n*minLenn∗minLencomparisons
where minLenminLen is
the length of the shortest string in the array.
Space complexity : O(1)O(1).
We only used constant extra space.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: