心情
今天沉迷罗翔老师的刑法课,涨了很多见识呐!
读题
leetcode: 14. 最长公共前缀
描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
测试用例:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
输入: [“dog”,“racecar”,“car”]
输出: “”
所有输入只包含小写字母 a-z
感觉挺简单哈。
思路
1:先排序,按照字符串排序
2:找到第一个和最后一个字符串,判断公共前缀
实现
public String longestCommonPrefix(String[] strs) {
String result = "";
if (strs != null && strs.length > 0) {
//作排序,字符串的排序先从前往后比较字符,最后比较长度
Arrays.sort(strs);
//此时第一位和最后一位的共同前缀即为结果
char[] first = strs[0].toCharArray();
char[] last = strs[strs.length - 1].toCharArray();
//获取两个数组的共同部分
for (int i = 0; i < first.length; i++) {
if (first[i] == last[i]) {
result += String.valueOf(first[i]);
} else {
break;
}
}
}
return result;
}
提交
参考题解的思路,我给出了更优化的写法,用时少了一半呢。
新知识-字典树
class Solution {
public class TrieNode {
int count;//计数,用于判断此层字符的个数
boolean isEnd = false;//单词结束
TrieNode[] nextNode = new TrieNode[26];
public TrieNode() {
count = 0;
isEnd = false;
}
//向字典中插入字符串
public int insert(String str) {
if (this == null || str.length() == 0) {
return 0;
}
TrieNode node = this;
char[] c = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
//如果该分支不存在,创建一个新节点
if (node.nextNode[c[i] - 'a'] == null) {
node.nextNode[c[i] - 'a'] = new TrieNode();
//若是当前后续有新节点,则当前节点count++,一般来说就是1,如果分叉就是1+
node.count ++;
}
node = node.nextNode[c[i] - 'a'];
}
//此时root为最后的节点,节点结尾的单词数+1
node.isEnd = true;
return 1;
}
}
//最长公共前缀树实现
public String longestCommonPrefix(String[] strs) {
String result = "";
if (strs != null && strs.length > 0) {
TrieNode node = new TrieNode();
for (int i = 0; i < strs.length; i++) {
if (node.insert(strs[i]) == 0) {
return "";
}
}
//找到count=1且isEnd为false的节点
while (node != null && node.count == 1 && node.isEnd == false) {
for (int i = 0; i < 26; i++) {
if(node.nextNode[i] != null) {
result += String.valueOf((char)('a' + i));
node = node.nextNode[i];
break;
}
}
}
}
return result;
}
}
结合评论区大神的C++解法,我翻成了java版本
竟然找不到java版本关于字典树的解法,emmm~
字典树又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。
关于字典树的用途倒是挺有趣:当我们要查询单词leetcode时,hash表必须等待用户把单词leetcode输入完毕才能hash查询,字典树就不需要输入完整的单词了。所以经常被搜索引擎系统用于文本词频统计。