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];
}
}
文章描述了一个编程挑战,要求判断一个给定字符串是否能被字典中的单词序列划分。首先尝试了朴素的递归方法,但由于时间复杂度高导致超时。接着,作者采用动态规划优化解决方案,通过创建一个布尔数组表示字符串的前缀是否可由字典单词表示,从而降低时间复杂度。
512

被折叠的 条评论
为什么被折叠?



