lc139. 单词拆分

原题链接
注意:本文的回溯代码会出现超时异常,仅供理解题目和拓展思路使用

class Solution {
//25min 回溯
public:
        map<char, vector<string>> Dict;
        int end ;
public:
    bool canMatch(string word, char arr[], int pos){
        int len = word.size();
        char wordArr[len + 1];
        strcpy(wordArr, word.c_str());
        for(int i = 0; i < len; i++){
            if(arr[pos + i] != wordArr[i]) return false;
        }
        return true;
    }
    bool backtrack(char arr[], int pos){
        if(pos >= end) return true;
        if(Dict[arr[pos]].empty()) return false;
        bool ans = false;
        for(int i = 0; i < Dict[arr[pos]].size(); i++){
            if(Dict[arr[pos]][i].size() <= end - pos && canMatch(Dict[arr[pos]][i], arr, pos)){
                ans = ans || backtrack(arr, pos + Dict[arr[pos]][i].size());
                if(ans == true) break;
            }
        }
        return ans;
    }
    bool wordBreak(string s, vector<string>& wordDict) {

        end = s.size();

        for(int i = 0; i < wordDict.size(); i++){
            char arr[wordDict[i].size() + 1];
            strcpy(arr, wordDict[i].c_str());

            Dict[arr[0]].push_back(wordDict[i]);
        }
        char sArr[s.size() + 1];
        strcpy(sArr, s.c_str());

        return backtrack(sArr, 0);
    }
};

你可能感兴趣的:(算法)