Created
June 23, 2014 06:39
-
-
Save gabhi/b257d94928308cd989d7 to your computer and use it in GitHub Desktop.
word break
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
Map<String, String> memoized; | |
String SegmentString(String input, Set<String> dict) { | |
if (dict.contains(input)) return input; | |
if (memoized.containsKey(input) { | |
return memoized.get(input); | |
} | |
int len = input.length(); | |
for (int i = 1; i < len; i++) { | |
String prefix = input.substring(0, i); | |
if (dict.contains(prefix)) { | |
String suffix = input.substring(i, len); | |
String segSuffix = SegmentString(suffix, dict); | |
if (segSuffix != null) { | |
memoized.put(input, prefix + " " + segSuffix); | |
return prefix + " " + segSuffix; | |
} | |
} | |
memoized.put(input, null); | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment