177、单词替换

题目描述:
你需要输出替换之后的句子。

示例 1:

输入: dict(词典) = [“cat”, “bat”, “rat”]
sentence(句子) = “the cattle was rattled by the battery”
输出: “the cat was rat by the bat”
注:

输入只包含小写字母。
1 <= 字典单词数 <=1000
1 <= 句中词语数 <= 1000
1 <= 词根长度 <= 100
1 <= 句中词语长度 <= 1000

首先我们能想到的就是使用前缀树,新建一个类,用于表示每个节点,子孩子为一个数组,表示的是26个字母
代码:

class Solution {
   //	2019年7月24日08:55:43
	Mytree root = new Mytree();
	public String replaceWords(List<String> dict, String sentence) {
        adddict(dict);
        
        StringBuilder sBuilder = new StringBuilder();
        for (String string : sentence.split(" ")) {
			int index = search(string);
			String str = index > 0 ? string.substring(0,index):string;
			sBuilder.append(str).append(" ");
		}
         return new String(sBuilder).substring(0, sBuilder.length() - 1);
    }
	public int search(String tem){
		Mytree node = root;
		int index = 0;
		for (char i : tem.toCharArray()) {
			if(node.child[i - 'a'] == null && !node.isend){
				return 0;
			}
			if(node.isend)
				return index;
			index  ++;
			node = node.child[i - 'a'];
		}
		return index;
	}
	
	public void adddict(List<String> dict){
		for (String string : dict) {
			Mytree get = root;
			for (char c  : string.toCharArray()) {
				if(get.child[c - 'a'] == null){
					get.child[c - 'a'] = new Mytree();
				}
				get = get.child[c - 'a'];
			}
			get.isend = true;
		}
	}
}

class Mytree{
	boolean isend;
	Mytree child[] = new Mytree[26];
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值