题目:最长公共前缀
思路1:排序
所有字符串排序,然后只需找到第一个和最后一个元素的公共前缀。
思路2:分治
代码1:
import java.util.*;
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
if (strs == null || strs.length == 0) {
return "";
}
Arrays.sort(strs);
String str1 = strs[0];
String str2 = strs[strs.length - 1];
int index = 0;
String res = "";
while (index < str1.length() && index < str2.length()) {
if (str1.charAt(index) == str2.charAt(index)) {
res += str1.charAt(index);
}
else {
break;
}
index ++;
}
return res;
}
}
代码2:
import java.util.*;
public class Solution {
/**
*
* @param strs string字符串一维数组
* @return string字符串
*/
public String longestCommonPrefix (String[] strs) {
// write code here
if (strs == null || strs.length == 0) {
return "";
}
return recursion(strs, 0, strs.length - 1);
}
public String recursion (String[] strs, int start, int end) {
if (start == end) {
return strs[start];
}
int mid = start + (end - start) / 2;
String str1 = recursion(strs, start, mid);
String str2 = recursion(strs, mid + 1, end);
int index = 0;
String res = "";
while (index < str1.length() && index < str2.length()) {
if (str1.charAt(index) == str2.charAt(index)) {
res += str1.charAt(index);
}
else {
break;
}
index ++;
}
return res;
}
}