标签:
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"
.
思路:recursion。没有加if(s.equals(""))的时候一直报错,想了想终于明白为什么。像code最后是contains,进入另一层循环如果没有base case直接跳出到for循环,return false。注意base case。
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { if(s==null||wordDict==null) { return false; } if(s.equals("")) { return true; } for(int i=0;i<s.length();i++) { if(wordDict.contains(s.substring(0,i+1))) { if(wordBreak(s.substring(i+1),wordDict)) { return true; } else { wordDict.remove(s.substring(0,i+1)); } } } return false; } }
标签:
原文地址:http://www.cnblogs.com/Machelsky/p/5878175.html