Q:
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
A:
First, I used the naive approach.
I use the every string in wordDict to match the first part of the String s.
if they are equal, it continue to match the remaining part of the String s.
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
if(s.length()==0) return true;
for(String w:wordDict){
int n = w.length();
if(n<= s.length() && w.equals(s.substring(0,n))){
boolean res = wordBreak(s.substring(n,s.length()), wordDict);
if(res) return res;
}
}
return false;
}
}
However, this naive approach exceeds the time limit.
Time: O(n^2)
Then I use Dynamic Programming to solve this problem
initial state f[0] = true
f[i] means substring s[0...i-] matches wordDict
f[i]==true while f[j]==true && s[j...i-1] matches wordDict
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] f = new boolean[n+1];
f[0] = true;
for(int i=0;i<n;i++){
if(!f[i]) continue;
for(String w:wordDict){
if((i+w.length()<=n) && w.equals(s.substring(i,i+w.length()))){
f[i+w.length()] = true;
}
}
}
return f[n];
}
}