topic
Given a string s non-empty and non-empty dictionary wordDict comprising a word list, it is determined whether the space s can be split into one or more words appear in the dictionary.
Description:
Word in the dictionary can be reused when the split.
You can assume that there is no repetition of the word in the dictionary.
Example 1:
Input: s = "leetcode", wordDict = [ "leet", "code"]
Output: true
interpretation: returns true because "leetcode" can be split into "leet code".
Example 2:
Input: s = "applepenapple", wordDict = [ "apple", "pen"]
Output: true
interpretation: returns true because "applepenapple" can be split into "apple pen apple".
Note that you can re-use the word in the dictionary.
Example 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/word-break
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer
- dp [i] represents the substring [0, i) may be fully resolved if (initialized dp [0] = true, meaning a special case)
- State transition equation: if (dp [j] && s.substring (j, i) in the dictionary), dp [i] = true
- Time complexity of O (n ^ 2)
- The default value is a Boolean false
Code
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}