一、题目
二、思路(自己)
- 将sentence以空格为分隔符,把sentence中的单词抽出来组成一个数组
- 对sentence形成的数组进行遍历,如果dictionary中存在单词是其词根,则替换
class Solution { public String replaceWords(List<String> dictionary, String sentence) { String[] words=sentence.split(" "); String ans = ""; for (int i = 0; i < words.length; i++) { for (String s : dictionary) { if(words[i].startsWith(s)) words[i]=s; } words[i]+=" "; ans+=words[i]; } return ans.trim(); } }
三、题解(官方)
- 官方第一个方法与我的差不多
class Solution { public String replaceWords(List<String> dictionary, String sentence) { Set<String> dictionarySet = new HashSet<String>(); for (String root : dictionary) { dictionarySet.add(root); } String[] words = sentence.split(" "); for (int i = 0; i < words.length; i++) { String word = words[i]; for (int j = 0; j < word.length(); j++) { if (dictionarySet.contains(word.substring(0, 1 + j))) { words[i] = word.substring(0, 1 + j); break; } } } return String.join(" ", words); } }