試題請參見: https://leetcode.com/problems/word-break/
題目概述
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"
.
解題思路
DP問題.
使用數組isMatched[i]表示字符串s[0, i - 1]是否可以被劃分.
因此isMatched[s.length]表示字符串s是否可以被劃分.
若isMatched[i] == true, 表示s[0, i - 1]可以被劃分, 則需要同時滿足如下條件之一:
isMatched[0] == true
, 且s[0, i - 1]
在dict中isMatched[1] == true
, 且s[1, i - 1]
在dict中isMatched[2] == true
, 且s[2, i - 1]
在dict中- `…
isMatched[i - 1] == true
, 且s[i - 1, i - 1]
在dict中
例如: s = "aaaaa"
, dict = { "aaaa", "aaa" }
.
isMatched[1] == false
, 因爲"a"
不在dict中isMatched[2] == false
, 因爲"aa"
不在dict中isMatched[3] == true
, 因爲"aaa"
在dict中isMatched[4] == true
, 因爲"aaaa"
在dict中對於
isMatched[5]
, 因爲"aaaaa"
不在dict中- 進而需要判斷
isMatched[1] = true
且s[1...4]
在dict中, 顯然前者不成立 - 進而需要判斷
isMatched[2] = true
且s[2...4]
在dict中, 顯然前者不成立 - 進而需要判斷
isMatched[3] = true
且s[3...4]
在dict中, 顯然後者不成立 - 進而需要判斷
isMatched[4] = true
且s[4...4]
在dict中, 顯然後者不成立
- 進而需要判斷
因此isMatched[5] == false
.
源代碼
import java.util.HashSet;
import java.util.Set;
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
int length = s.length();
boolean[] isMatched = new boolean[length + 1];
isMatched[0] = true;
for ( int i = 1; i <= length; ++ i ) {
for ( int j = 0; j < i; ++ j ) {
if ( isMatched[j] && wordDict.contains(s.substring(j, i)) ) {
isMatched[i] = true;
break;
}
}
}
return isMatched[length];
}
public static void main(String[] args) {
Solution s = new Solution();
Set<String> set = new HashSet<String>();
set.add("leet");
set.add("code");
System.out.println(s.wordBreak("leetcode", set));
}
}