@leetcode最长公共前缀
题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例
输入: [“flower”,“flow”,“flight”,“fly”]
输出: “fl”
题解
找相同前缀需要相互比较;
可以通过两两顺次比较来做;
思路流:
0 flower
1 flow
2 flight
3 fly
0 flower
1 flow * flow*
2
3
0
1 flow
2 flight *fl*
3
0
1
2 fl
3 fly **fl**
通过temp来记录当前string;
初始状态temp是第一个字符串;
用j来卡住temp的长度;
核心算法:
for(j = 0;j<temp.length() && j<strs[i].length();j++){
if(temp.charAt(j) != strs[i].charAt(j)){
break;
}
}
temp= temp.substring(0,j);
java代码
class Solution {
public String longestCommonPrefix(String[] strs) {
int i;
int j;
if(strs.length == 0){
return "";
}
String temp= strs[0];
for(i = 1;i<strs.length;i++){//注意字符串长度length(),数组长度length
for(j = 0;j<temp.length() && j<strs[i].length();j++){
if(temp.charAt(j) != strs[i].charAt(j)){
break;
}
}
temp= temp.substring(0,j);//用j卡住temp
}
return temp;
}
}