java 解决Leetcode Longest Common Prefix 问题
查看题目点击这里
题目简介:
Write a function to find the longest common prefix string amongst an array of strings.
题目很简单:就是求所有字符串的相同的前缀;
解题思路:
先求出最短字符串,在遍历最短字符串,从前往后遍历,都存在就加入到StringBuilder中。
代码实现如下:
public class LongestCommonPrefix_1 {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
int length = Integer.MAX_VALUE, point = 0;
for (int i = 0; i < strs.length; ++i) {
if (strs == null || strs[i].length() == 0) {
return "";
}
if (strs[i].length() < length) {
point = i;
length = strs[i].length();
}
}
String signStr = strs[point];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < signStr.length(); ++i) {
if(match(strs,i,signStr.charAt(i))){
sb.append(signStr.charAt(i));
}else{
break;
}
}
return sb.toString();
}
/**
* 判断某个字符是否在所有字符串的指定位置都相同
* @param strs
* @param position
* @param sign
* @return
*/
private boolean match(String[] strs,int position,char sign){
for (int i = 0 ; i < strs.length ; ++i){
if(strs[i].charAt(position) != sign){
return false;
}
}
return true;
}
}
上面是按照题目来解的,假如不是最长的相同前缀呢,要是求相同的最长连续字符串呢,那这个题目就不是这么简单了,其实解法基本相似,也是遍历最短字符串,一次遍历,来求出最长连续字符串。代码如下:
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
int length = Integer.MAX_VALUE, point = 0;
for (int i = 0; i < strs.length; ++i) {
if (strs == null || strs[i].length() == 0) {
return "";
}
if (strs[i].length() < length) {
point = i;
length = strs[i].length();
}
}
String signStr = strs[point];
StringBuilder sb = new StringBuilder();
String tempStr = "";
for (int i = 0; i < signStr.length(); ++i) {
sb.append(signStr.charAt(i));
if (!isContains(strs, sb.toString())) {
sb.deleteCharAt(sb.length()-1);
if (tempStr.length() < sb.toString().length()) {
tempStr = sb.toString();
}
sb = new StringBuilder();
}
}
if (tempStr.length() < sb.toString().length()) {
tempStr = sb.toString();
}
return tempStr;
}
/**
* 判断某个字符串是否在某个字符数组中都包含
*
* @param containsStrArray
* @param judgeStr
* @return
*/
private boolean isContains(String[] containsStrArray, String judgeStr) {
for (int i = 0; i < containsStrArray.length; ++i) {
if (!containsStrArray[i].contains(judgeStr)) {
return false;
}
}
return true;
}
}
至此,OVER!!!