leetcode------Word Break
题目: |
Word Break |
通过率: | 22.6% |
难度: | 中等 |
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数组进行维护示例,但是在判断时要判断起始位置是否为true,例子如下
leetcode
i=1,j=0时取(0,1)>>l
i=2,j=0时取(0,2)>>le
......
i=4,j=0时res[j]=true并且(0,4为leet存在,所以res[4]=true
。。。
i=8,j=4时res[4]=true,所以code在dict里面
直接看代码:
1 public class Solution { 2 public boolean wordBreak(String s, Set<String> dict) { 3 int len=s.length(); 4 boolean [] res=new boolean[len+1]; 5 res[0]=true; 6 for(int i=1;i<=len;i++){ 7 for(int j=0;j<i;j++){ 8 if(res[j]&&dict.contains(s.substring(j, i))){ 9 res[i]=true; 10 break; 11 } 12 } 13 } 14 return res[len]; 15 } 16 }