Word Break

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

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

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

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<string> buf;
	    int maxLen = 0;
	    for (unordered_set<string>::iterator it = wordDict.begin(); it != wordDict.end(); it++)
	    {   
		    if (it->length() > maxLen)
		    {
			    maxLen = it->length();
		    }
	    }

	    int len = 1;
	    while (len <= maxLen && s.length() > 0)
	    {
		    for (; len <= maxLen; len++)
		    {
			    if (wordDict.find(s.substr(0, len)) != wordDict.end())
			    {
				    buf.push_back(s.substr(0, len));
				    break;
			    }
		    }

		    if (len <= maxLen)
		    {
			    s = s.substr(len, string::npos);
			    len = 1;
		    }
		    else if (!buf.empty())
		    {
			    string temp = buf.back();
			    buf.pop_back();
			    s = temp + s;
			    len = temp.length() + 1;
		    }
	    }

	    return s.length() == 0;
    }
};


你可能感兴趣的:(Word Break)