1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package com.demo.s139;
import java.util.HashSet; import java.util.List; import java.util.Set;
public class Solution {
public boolean wordBreak(String s, List<String> wordDict) { if(wordDict.size() == 0) return false; Set<Integer> wordLength = new HashSet<>(); for (String word : wordDict) { wordLength.add(word.length()); } Set<String> dict = new HashSet<>(wordDict); Set<String> wrongSet = new HashSet<>(); return matchWords(s, dict, wordLength, wrongSet); }
public boolean matchWords(String s, Set<String> dict, Set<Integer> wordLength, Set<String> wrongSet) { if("".equals(s) || dict.contains(s)) return true; for(Integer j : wordLength) { if(j > s.length()) return false; String sub = s.substring(0, j); if(dict.contains(sub)) { String subEnd = s.substring(j); if(!wrongSet.contains(subEnd) && matchWords(subEnd, dict, wordLength, wrongSet)) { return true; } else { wrongSet.add(subEnd); } } } return false; } }
|