Word Break

题目:

Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.

Example: Given s = "lintcode", dict = ["lint", "code"].

Return true because "lintcode" can be break as "lint code".

分析:

这题目只要注意i, j表示的物理意义就好了,其实i - j表示前若干个元素,然后substr(i - j, j)表示,前i - j个的后续j个元素。

这题目有个隐藏考点是需要注意字典的maxLength。英文单词最大长度为20,也就是i18n,如果j超过这个范围,则不用考虑。

// state: f[i] meaning the first i chars can be broke;
// function: f[i] = true, iff there exist f[i - j] = true and i - j ~ i is in dict;
// init: f[0] = true;
// return f[n];

解法:

class Solution {
public:
    /**
     * @param s: A string s
     * @param dict: A dictionary of words dict
     */
    bool wordBreak(string s, unordered_set<string> &dict) {
        // write your code here

        // state: f[i] meaning the first i chars can be broke;
        // function: f[i] = true, iff there exist f[j] = true (j < i) and j + 1 ~ i is in dict;
        // init: f[0] = true;
        // return f[n];

        int n = s.size();
        if (n == 0) {
            return true;
        }
        vector<bool> f(n + 1, false);
        f[0] = true;

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= 21 && j <= i; j++) {
                if (f[i - j] == false) {
                    continue;
                }
                string substr = s.substr(i - j, j);
                if (dict.find(substr) != dict.end() ) {
                    f[i] = true;
                    break;
                }
            }
        }

        return f[n];
    }
};

results matching ""

    No results matching ""