Skip to content

Instantly share code, notes, and snippets.

@ShikaSD
Created December 17, 2019 18:55
Show Gist options
  • Save ShikaSD/41c85b02fd9d50cd2e7fdc30e0ff58ed to your computer and use it in GitHub Desktop.
Save ShikaSD/41c85b02fd9d50cd2e7fdc30e0ff58ed to your computer and use it in GitHub Desktop.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return check(s, wordDict, 0);
}
private HashMap<Integer, Boolean> cache = new HashMap<>();
public boolean check(String s, List<String> wordDict, int index) {
if (index == s.length()) {
return true;
}
Boolean cachedValue = cache.get(index);
if (cachedValue != null) {
return cachedValue;
}
for (String word : wordDict) {
// System.out.println("checking " + word + " on index " + index);
if (matches(s, word, index)) {
if (check(s, wordDict, index + word.length())) {
return true;
}
}
}
cache.put(index, false);
return false;
}
public boolean matches(String s, String word, int index) {
if (index + word.length() > s.length()) {
return false;
}
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != s.charAt(index + i)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment