【Leetcode139】Word Break

Harmony is a dynamic programming problem, because every place possible as a dividing point in the "may" is used as the point of division, segmentation does not necessarily here, for example:

I have s = "aaaaaaa" of 7 'a', the dictionary { "aaa", "aaaa"}. If the first six divided into 2 groups a "aaa", then the rest of a division will not, so that the index is divided into the complete Can be discussed here, and then e.g.

index1, index2, index3 index represents the position of the three, if you want to know 1 ~ index3 Can break down, we know 0 ~ index2 Can break down, the rest is judgment index2 + 1 ~ index3 is not the word, if not I can not explain what that says if you really here divided, then the back is not established, so although 0 ~ index2 can complete split, we do not accept this proposal. Keep going, between 0 ~ index1 also can be completely separated, then to analyze index1 ~ index3 is not the word. . . Note here that the presence or absence of between indexx ~ index3 word rather than split Can

Dynamic programming is characterized by reverse push, to solve the problem now based on sub-problems. 

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        std::vector<bool> flag(s.length()+1, false);
        flag[0] = true;
        for(int i = 0; i < s.length(); ++i){//包括i可分,保存在i+1位置,例如0位置可分的flag在1
            for(int j = i-1; j >= -1; --j){
                if(flag[j+1] && wordSet.count(s.substr(j+1, i-j))){
                    flag[i+1] = true;
                    break;
                }
            }
        }
        return flag.back();
    }
};

Note that the c ++ to the code;

1, here the unorderd_set, the benefits of unordered hash table, fast search speed, set the map compared to only one type of data needs to be saved;

2, I did not even really think vector can be initialized unordered_set, it certainly can be set up;

3, flag setting for a flag to OFF position, whether separable, this flag [i] is turned off is actually saved and comprises s [i-1] if separable, flag [0] is saved s [-1], the significance of this position is that, out of a virtual initial, that is, is s [-1] is willing to present such a thing does not exist, because it is required to initialize the s [0] corresponding flag bool

 

Published 112 original articles · won praise 15 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_39458342/article/details/104957538