LeetCode 648. Replace Words (单词替换)
题目标签:HashMap
题目给了我们一个array 的 root, 让我们把sentence 里面得每一个word 去掉它得 successor。
把每一个root 存入hash set,然后遍历sentence 里面得每一个 word, 从index 1 开始遍历 如果有找到这个root,就把这个word 替换掉。具体看code。
Java Solution:
Runtime: 158 ms, faster than 25.65%
Memory Usage: 50.3 MB, less than 83.90%
完成日期:04/04/2019
关键点:把root 存入hash set
class Solution { public String replaceWords(List<String> dict, String sentence) { Set<String> set = new HashSet<>(); String[] words; StringBuilder result = new StringBuilder(); for(String str : dict) set.add(str); words = sentence.split(" "); for(String word: words) { for(int i=1; i<word.length(); i++) { if(set.contains(word.substring(0, i))) { word = word.substring(0, i); break; } } result.append(word + " "); } return result.deleteCharAt(result.length() - 1).toString(); } }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/