Write a function to find the longest common prefix string amongst an array of strings.
A:
不知道什么考点, 反正,就是从最右边一个个字母地数呗。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0){
return "";
}
int endIndex = -1;
// find the minimum length of strs[]
int minLength = strs[0].length();
for (int i = 1; i < strs.length; i++) {
if (minLength > strs[i].length()) {
minLength = strs[i].length();
}
}
int numMatched;
char ch;
for (int i = 0; i < minLength; i++) {
ch = strs[0].charAt(i);
numMatched = 1;
for (int j = 1; j < strs.length; j++) {
if(strs[j].charAt(i) == ch){
numMatched ++;
}
}
if(numMatched == strs.length){
endIndex++;
}else{
break;
}
}
return strs[0].substring(0,endIndex+1);
}
}
Mistakes:
1: 考虑到 prefix 可能是空, 那么 如果我们在 后面返回的时候 endIndex+1;
则会导致 错误。
错误在于, 我们一直把endIndex 看做是 inclusive的, 但是,我们开始就给他赋值为0, 导致,总会返回第一个节点。 ----------------- 》 倒回去, 我们假设,开始节点为 -1 。
Learne:
------------------------第二遍-----------
当 我们找到一个不同的之后,不仅仅要对endIndex赋值,而且还要跳出来
if (breakAtHere) {
endIndex = i;
break;
}
因此,上面,需要加一个break语句。
No comments:
Post a Comment