Word Break Problem
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words.
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Discussion :
Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice, cream, icecream, man, go, mango}
Input: ilike
Output: Yes
The string can be segmented as "i like".
Discussion :
public boolean wordBreak(String s, List<String> wordDict) { if (s == null || s.length() == 0) return false; int n = s.length(); boolean[] dp = new boolean[n]; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { String sub = s.substring(j, i + 1); if (wordDict.contains(sub) && (j == 0 || dp[j - 1])) { dp[i] = true; break; } } } return dp[n - 1]; }
Comments
Post a Comment