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"
.
查看字符串是否由字典中的单词组成。
1、暴力递归,果断超时。
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { return helper(s,0,wordDict); } public boolean helper(String s,int start,Set<String> wordDict ){ if( start == s.length() ) return true; for( int i = s.length();i > start ;i--){ if( wordDict.contains( s.substring(start,i) ) ){ if( helper(s,i,wordDict) ) return true; } } return false; } }
2、dp,基本达到最快。
int len = s.length(),maxLen = 0; boolean[] dp = new boolean[len]; for( String str : wordDict ){ maxLen = Math.max(maxLen,str.length()); } for( int i = 0 ;i<len;i++){ for( int j = i;j>=0 && i-j<maxLen;j-- ){ if( ( j == 0 || dp[j-1] == true ) && wordDict.contains(s.substring(j,i+1)) ){ dp[i] = true; break; } } } return dp[len-1];