今天和大家聊的问题叫做 单词拆分,我们先来看题面:
https://leetcode-cn.com/problems/word-break/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
样例
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
这个题可以使用动态规划来解决。动态规划最重要的是状态的定义,好的状态定义能够使解题非常简便。
状态定义:
dp[i]:长度为i的字符串能否拆成wordDict里边的单词组合
状态转移方程:
dp[i] = dp[j] && substr(j, i) in wordDict, (0 <= j < i)
初始状态:
dp[0]=true
以下是C++代码:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<int> dp(s.size()+1, 0);
dp[0] = 1;
unordered_set<string> st(wordDict.begin(), wordDict.end());
for(int i = 1; i <= s.size(); i++)
{
for(int j = 0; j < i; j++)
{
auto pos = st.find(s.substr(j, i-j));
if(dp[j] && pos != st.end())
{
dp[i] = 1;
break;
}
}
}
return dp[s.size()];
}
};
好了,今天的文章就到这里。