原题网址:https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
方法一:暴力求解。
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
if (strs.length == 1) return strs[0];
int i=0;
outer: for(;;i++) {
if (i>=strs[0].length()) break outer;
for(int j=1; j<strs.length; j++) {
if (i>=strs[j].length()) break outer;
if (strs[0].charAt(i) != strs[j].charAt(i)) break outer;
}
}
return strs[0].substring(0,i);
}
}
另一种实现:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
int prefix = 0;
char[][] sas = new char[strs.length][];
for(int i=0; i<strs.length; i++) {
if (strs[i] == null) return "";
sas[i] = strs[i].toCharArray();
}
for(int i=0; ; i++) {
for(int j=0; j<sas.length; j++) {
if (i>=sas[j].length) return strs[j].substring(0, i);
if (j>0 && sas[j][i] != sas[j-1][i]) return strs[j].substring(0, i);
}
}
}
}
方法二:使用Trie
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
Trie root = new Trie();
for(int i=0; i<strs.length; i++) {
char[] sa = strs[i].toCharArray();
Trie node = root;
node.count ++;
for(int j=0; j<sa.length; j++) {
node = node.append(sa[j]);
node.count ++;
}
}
int len = 0;
Trie node = root;
for(; node.size==1 && node.nexts[node.trans[0]].count==strs.length; node=node.nexts[node.trans[0]], len++);
return strs[0].substring(0, len);
}
}
class Trie {
int count;
char[] trans = new char[256];
int size;
Trie[] nexts = new Trie[256];
Trie append(char ch) {
if (nexts[ch] == null) {
trans[size++] = ch;
nexts[ch] = new Trie();
}
return nexts[ch];
}
}