코테준비 - Word Break

정상화·2023년 2월 26일

LeetCode

목록 보기
135/222

Word Break

class Solution {
public:
    bool wordBreak(string s, vector<string> &wordDict) {
        unordered_set<string> wordSet;
        vector<bool> DP(301, true);
        for (auto &word: wordDict) {
            wordSet.insert(word);
        }

        return splitable(DP, wordSet, s, 0);
    }

    bool splitable(vector<bool>& DP, unordered_set<string> &wordSet, string s, int start) {
        for (int cut = start + 1; cut <= s.length(); cut++) {
            if (wordSet.find(s.substr(start, cut - start)) != wordSet.end()
                && DP[cut]
                && splitable(DP, wordSet, s, cut)) {
                return true;
            }
        }
        DP[start] = start == s.length();
        return start == s.length();
    }
};
profile
백엔드 희망

0개의 댓글