LeetCode 139 Word Break DP+map
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.
Solution
和 \(CF\) 有道题很相似,同样是利用 \(map\) 来直接映射。这次不一样的是,我们可以分割成很多个子串,问能否组成 \(s\). 考虑 \(dp[i]\) 表示区间 \(s[0,i)\) 是否可以组成。
所以我们枚举最后的端点 \(i\in[1,s.length]\),在子串\(s[0,i)\) 内部进行转移,即:
\[dp[0,j)\ \& \ s.substr(j,i-j) 
\]
点击查看代码
class Solution {
private:
    int dp[302];
    map<string, int> mp;
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int n = s.length();
        for(int i=0;i<wordDict.size();i++)
            mp[wordDict[i]]=1;
        // dp[i]: s[0, i) true or false
        dp[0] = 1;
        for(int i=1;i<=n;i++){// end point
            for(int j=0;j<i;j++){
                if(dp[j]){
                    string tmp = s.substr(j,i-j);
                    if(mp[tmp]){
                        dp[i] = true; break;
                    }
                }
            }
        }
        return dp[n];
    }
};
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号