题目:
In English, we have a concept called root
, which can be followed by some other words to form another longer word - let's call this word successor
. For example, the root an
, followed by other
, which can form another word another
.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor
in the sentence with the root
forming it. If a successor
has many roots
can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
Note:
- The input will only have lower-case letters.
- 1 <= dict words number <= 1000
- 1 <= sentence words number <= 1000
- 1 <= root length <= 100
- 1 <= sentence words length <= 1000
class Solution {
public String replaceWords(List<String> dict, String sentence) {
//给定字符串,和词根,对字符串中包含词根的单词只保留词根,返回最后的字符串
//给定字符串,和词根,对字符串中包含词根的单词只保留词根,返回最后的字符串
//思路:使用set存储词根,然后对sentence字符串进行截断单词处理,对处理后的每个单词进行匹配
//一旦匹配到最短的词根,则将该词根写入该单词的数组中
//对单词进行截取
char [] chs=sentence.toCharArray();
int blank=0;
for(int i=0;i<chs.length;i++){
if(chs[i]==' '){
//有多少个空格符
blank++;
}
}
//创建单词数组,单词数量为空格+1
String [] str=new String[blank+1];
//切分单词
int start=0;
int count=0;
for(int i=0;i<chs.length;i++){
if(chs[i]==' '){
str[count++]=sentence.substring(start,i);
start=i+1;
}else if(i==chs.length-1){
//最后一个单词
str[count++]=sentence.substring(start,i+1);
}
}
//创建词根set
HashMap<String,Integer> hm=new HashMap<String,Integer>();
int minLen=Integer.MAX_VALUE;
for(String s:dict){
hm.put(s,s.length());
minLen=Math.min(minLen,s.length());
}
//对单词进行匹配,直接从最小的字符串长度开始匹配
for(int i=0;i<str.length;i++){
//遇到长度小于minLen的直接跳过
if(str[i].length()<minLen) continue;
StringBuilder tempStr=new StringBuilder();
tempStr.append(str[i].substring(0,minLen));
for(int j=minLen;j<str[i].length();j++){
//每添加一个字符串,跟哈希表匹配一次,匹配成功,直接替换该单词,退出当前单词
if(hm.get(tempStr.toString())!=null){
//说明存在词根
str[i]=tempStr.toString();
break;
}
tempStr.append(str[i].substring(minLen,minLen+1));
}
}
//将单词输出
StringBuilder sb=new StringBuilder();
for(int i=0;i<str.length;i++){
sb.append(str[i]);
if(i!=str.length-1){
//最后一个不用添加空格
sb.append(" ");
}
}
return sb.toString();
}
}
分析2-参考答案(推荐):
class Solution {
private class TrieNode {
char val;
TrieNode[] children;
boolean isWord;
public TrieNode(char val) {
this.val = val;
this.children = new TrieNode[26];
this.isWord = false;
}
}
public String replaceWords(List<String> dict, String sentence) {
String[] tokens = sentence.split(" ");
TrieNode trie = buildTrie(dict);
return replaceWords(tokens, trie);
}
private String replaceWords(String[] tokens, TrieNode root) {
StringBuilder stringBuilder = new StringBuilder();
for (String token : tokens) {
stringBuilder.append(getShortestReplacement(token, root));
stringBuilder.append(" ");
}
return stringBuilder.substring(0, stringBuilder.length()-1);
}
private String getShortestReplacement(String token, final TrieNode root) {
TrieNode temp = root;
StringBuilder stringBuilder = new StringBuilder();
for (char c : token.toCharArray()) {
stringBuilder.append(c);
if (temp.children[c - 'a'] != null) {
if (temp.children[c - 'a'].isWord) {
return stringBuilder.toString();
}
temp = temp.children[c - 'a'];
} else {
return token;
}
}
return token;
}
private TrieNode buildTrie(List<String> dict) {
TrieNode root = new TrieNode(' ');
for (String word : dict) {
TrieNode temp = root;
for (char c : word.toCharArray()) {
if (temp.children[c - 'a'] == null) {
temp.children[c - 'a'] = new TrieNode(c);
}
temp = temp.children[c - 'a'];
}
temp.isWord = true;
}
return root;
}
}