题目:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
题意及分析:给出一个字符串s和一个字典list,判断由字典中的单词能否组成字符串s。这道题可以用动态规划的思路求解,对于s的任意一个子字符串subString1=s.subString(0,i+1),如果该子字符串能够被字典中单词构成,那么只有一种情况,即有一个能被字典中单词构成的子字符串加上一个在字典中的单词,对字符串进行遍历即可。这里需要注意的是subString操作时左闭右开的。
代码:
public class Solution { public boolean wordBreak(String s, List<String> wordDict) { int length=s.length(); boolean[] res=new boolean[length+1]; //记录到第0个字符到第i个字符的子字符串能否被字典划分 res[0]=true; for(int i=1;i<=length;i++){ //s的每个子字符串求解 for(int j=0;j<i;j++){ if(res[j]&&wordDict.contains(s.substring(j, i))){ res[i]=true; break; } } } return res[length]; } }