Leetcode 648 单词替换
地址: https://leetcode-cn.com/problems/replace-words/
代码:
/**
* @Author linchen.wcy
*/
class Solution {
class TreeNode {
char data;
List<TreeNode> child;
TreeNode parent;
boolean isWord;
public TreeNode() {
this.child = new ArrayList<>();
this.data='#';
}
}
public TreeNode build(List<String> dict) {
TreeNode root = new TreeNode();
for (int i = 0; i < dict.size(); i++) {
insertOnebyOne(dict.get(i), root);
}
return root;
}
private void insertOnebyOne(String s, TreeNode root) {
int pos = 0;
// 找共性
while (pos < s.length()) {
int pre = pos;
for (int i = 0; i < root.child.size()&&pos<s.length(); i++) {
if (root.child.get(i).data == s.charAt(pos)) {
root = root.child.get(i);
if(pos == s.length()-1){
root.isWord=true;
}
pos++;
}
}
if (pre == pos) break;
}
// 共性如果包含不全,则添加节点
while (pos < s.length()) {
TreeNode temp = new TreeNode();
temp.data = s.charAt(pos);
pos++;
if (pos == s.length()) temp.isWord = true;
temp.parent = root;
root.child.add(temp);
root = temp;
}
}
public String calc(TreeNode root, String sentence) {
StringBuilder sb = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = replaceWords0(root, words[i]);
sb.append(words[i] + " ");
}
return sb.substring(0, sb.length() - 1);
}
// bfs is faster!
public String replaceWords0(TreeNode root, String word) {
TreeNode current = root;
LinkedList<TreeNode> queue = new LinkedList<>();
for (int i = 0; i < root.child.size(); i++) {
if (root.child.get(i).data == word.charAt(0)) {
queue.add(root.child.get(i));
break;
}
}
if (queue.isEmpty()) return word;
int pos = 1;
while (!queue.isEmpty() && pos <word.length()) {
TreeNode first = queue.poll();
if (first.isWord) {
StringBuilder sb = new StringBuilder();
populate(sb, first);
return sb.toString();
} else {
for (int i = 0; i < first.child.size(); i++) {
{
if (first.child.get(i).data == word.charAt(pos)) {
queue.add(first.child.get(i));
pos++;
break;
}
}
}
}
}
return word;
}
private void populate(StringBuilder sb, TreeNode first) {
while (first.data != '#') {
sb.insert(0,first.data);
first=first.parent;
}
}
public String replaceWords(List<String> dictionary, String sentence) {
TreeNode root = build(dictionary);
return calc(root, sentence);
}
}