您的位置:首页 > 其它

139. Word Break

2016-11-06 09:43 218 查看
Given a string s and a dictionary of words dict, determine if
s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given
s =
"leetcode"
,
dict =
["leet", "code"]
.

Return true because
"leetcode"
can be segmented as
"leet code"
.

分析:动态规划;

设置一个boolean数组,其中每个元素用来代表字符串s的前i个字符串,是不是能够用set中的字符串表示。

时间复杂度:O(N*N)

空间复杂度:O(N)

public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
int n=s.length();
boolean[] flag=new boolean[n+1];
flag[0]=true;
for(int i=1;i<=n;i++){
for(int j=0;j<=i;j++){
String temp=s.substring(j,i);
if(flag[j]&&wordDict.contains(temp)){
flag[i]=true;
}
}
}
return flag
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: