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"
.
?
import java.util.Set; public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { boolean[] flag = new boolean[s.length()]; return solve(s, 0, wordDict, flag); } private boolean solve(String s, int now, Set<String> wordDict, boolean[] flag) { // TODO Auto-generated method stub if (now >= s.length()) { return true; } if (flag[now]) { return false; } flag[now] = true; for (int i = now; i < s.length(); i++) { if (wordDict.contains(new String(s.getBytes(), now, i-now+1)) && solve(s, i+1, wordDict, flag)) { return true; } } return false; } }
?
原文:http://hcx2013.iteye.com/blog/2247393