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
|
public class WordBreak { public boolean wordBreak(String s, Set<String> wordDict) { if (s == null || s.isEmpty()) { return true; } boolean[] map = new boolean[s.length() + 1]; map[0] = true; for (int i = 0; i < s.length(); i++) { if (!map[i]) { continue; } for (String str : wordDict) { int l = str.length(); int end = i + l; if (end > s.length()) { continue; } if (map[end]) { continue; } String sub = s.substring(i, end); if (sub.equals(str)) { map[end] = true; } } } return map[s.length()]; } }
|