Skip to content

Latest commit

 

History

History
75 lines (58 loc) · 2.12 KB

0139. 单词拆分 [Medium] [Word Break].md

File metadata and controls

75 lines (58 loc) · 2.12 KB

Given a string s and a dictionary of strings wordDict , return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false

Constraints:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

题目:给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。**注意:**不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。

思路:DFS。

工程代码下载

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        set<string> st(wordDict.begin(), wordDict.end());
        vector<int> memo(s.size(), -1);
        return helper(s, st, 0, memo);
    }
private:
    bool helper(const string& s, const set<string>& st, int idx, vector<int>& memo){
        const int n = s.size();
        if(idx == n)
            return true;

        if(memo[idx] != -1)
            return memo[idx];

        for(int i = idx; i < n; ++i){
            if(st.find(s.substr(idx, i - idx + 1)) != st.end() &&
              helper(s, st, i + 1, memo)){
                memo[idx] = 1;
                return true;
            }
        }
        memo[idx] = 0;
        return false;
    }
};