Created
December 17, 2019 18:55
-
-
Save ShikaSD/41c85b02fd9d50cd2e7fdc30e0ff58ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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