问题
Problem:
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”.
即:是否可以把一个字符串拆分成单词字典dict的一个或多个词
动态规划解法
因为这两天接触了动态规划,所以我准备试试能不能用dp算法去解出这道题。
思路:
-
- 建一个数组来存储状态dp,空串或前面是dict里单词的字符的index所在的状态是true
- 定义一个初始状态,dp[0] = true,即空串为true
- 根据dict里面的单词字符创去和以从字符串第一个字符开始的字符串比较,如果相等,给字符串中的这个单词的下一个字符的dp[nextChar] = true;
- 根据状态进行一些判断
代码:
public boolean wordBreak(String str ,Set<String> dict {
boolean[] dp = new boolean[str.length()+1];
dp[0] = true;//set first to be true, why?
//Because we need initial state
for (int i = 0; i < str.length(); i++) {
//should continue from match position
if (!dp[i])
continue;
for (String word : dict) {
int len = word.length();
int end = i + len;
if (end > str.length())
continue;
if (dp[end])
continue;
if (str.substring(i , end).equals(word)) {
dp[end] = true;
}
}
}
return dp[str.length()];
}
@Test
public void testWordBreak(){
String str = "leetcode";
String[] strs = {"leet", "code"};
Set<String> dict = new HashSet<String>(Arrays.asList(strs));
System.out.println(wordBreak(str, dict));
}
递归法 (转载)
我又研究一下其他人的方法,记录一下递归法
- 理解思路:
- 1.这是一个递归
- 2.递归的方法是解题的核心
- 3.递归需要有一个结束条件,本题的结束条件就是start == s.length()
public boolean wordBreak(String s, Set<String> dict) {
return wordBreakHelper(s, dict, 0);
}
public boolean wordBreakHelper(String s, Set<String> dict, int start){
if(start == s.length())
return true;
for(String a: dict){
int len = a.length();
int end = start+len;
//end index should be <= string length
if(end > s.length())
continue;
if(s.substring(start, start+len).equals(a))
if(wordBreakHelper(s, dict, start+len))
return true;
}
return false;
}
正则表达式法 (转载)
public static void main(String[] args) {
HashSet<String> dict = new HashSet<String>();
dict.add("go");
dict.add("goal");
dict.add("goals");
dict.add("special");
StringBuilder sb = new StringBuilder();
for(String s: dict){
sb.append(s + "|");
}
String pattern = sb.toString().substring(0, sb.length()-1);
pattern = "("+pattern+")*";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher("goalspecial");
if(m.matches()){
System.out.println("match");
}
}