[LeetCode] 139 Word Break(BFS统计层数的方法)

原题地址:

https://leetcode.com/problems/word-break/description/

 

题目:

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

 

解法:

这道题目利用动态规划做出来,不得不说想法是很巧妙的,我也是参考了网上的代码才AC了。因此,先放代码,等我完全弄懂再补充吧:

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        if(s == "" || s.size() == 0) {
            return true; 
        }
        unordered_map<int, bool> res;
        for (int i = 0; i <= s.size(); i++) {
            res[i] = false;
        }
        res[0] = true;
        for (int i = 0; i < s.size(); i++) {
            string str = s.substr(0, i + 1);
            for (int j = 0; j <= i; j++) {
                if (res[j] && find(wordDict.begin(), wordDict.end(), str) != wordDict.end()) {
                    res[i + 1] = true;
                    break;
                }
                str = str.substr(1, str.size() - 1);
            }
        }
        return res[s.size()];
    }
};

 

2018.1.7更新

另外的做法(其实就是换了一种统计层数的方法):

class Solution {
public:
   bool isConnected(string a, string b) {
        int num = 0;
        for (int i = 0; i < a.size(); i++) {
            if (a[i] != b[i]) num++;
        }
        return num == 1;
    }
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int res = 1;
        queue<string> s;
        s.push(beginWord);
        while (!s.empty()) {
            int size = s.size();
            for (int i = 0; i < size; i++) {
                string str = s.front();
                s.pop();
                if (str == endWord) {
                    return res;
                }
                for (vector<string>::iterator iter = wordList.begin(); iter != wordList.end();) {
                    if(isConnected(str, *iter)) {
                        s.push(*iter);
                        iter = wordList.erase(iter);
                    } else {
                        iter++; 
                    }
                }
            }
            res++;
        }
        return 0;
    }
};

 

posted @ 2017-10-16 18:43  fengzw  阅读(272)  评论(0编辑  收藏  举报