word break

  • 问题来源
  • 问题简介

    设计一个函数,接收一个字符串s和一个字典dict(字符串列表,无重复),要求返回s是否能被若干个dict里的字符串构成。


解题思路


时间复杂度 空间复杂度
O(未知) O(未知)

Code

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int size = s.length();
        vector<bool> avalible(size + 1, false);

        unordered_set<string> set;
        for (auto str : wordDict) {
            set.insert(str);
        }
        auto notFound = set.end();
        avalible[0] = true;
        for (int i = 1; i <= size; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (avalible[j] && set.find(s.substr(j, i - j)) != notFound) {
                    avalible[i] = true;
                    break;
                }
            }
        }
        return avalible[size];
    }
};

运行结果

Word Break