139. Word Break

 这里的result[0] = true值得注意

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int length1 = wordDict.size();
        int maxlength = 0;
        for(int i = 0;i < length1;i++){
            if(wordDict[i].length() > maxlength)
                maxlength = wordDict[i].length();
        }
        int length2 = s.length();
        vector<bool> result(length2+1);
        result[0] = true;
        for(int i = 1;i <= length2;i++){
            result[i] = false;
            for(int j = 1;j <= maxlength && j <= i;j++){
                if(result[i-j] == false)
                    continue;
                else{
                    string str1 = s.substr(i-j,j);
                    for(int k = 0;k < length1;k++){
                        if(str1 == wordDict[k]){
                            result[i] = true;
                            break;
                        }
                    }
                }
            }
        }
        return result[length2];
    }
};

 substr函数的第一个参数是开始的位置,第二个参数不是结束的位置,而是个数

原文地址:https://www.cnblogs.com/ymjyqsx/p/7482405.html