Wednesday, November 13, 2013

Leetcode problem : Word break

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".

Code

bool wb_r(int row,const string& s, unordered_set<string> &dict){
    if(row == 0)
        return true;
    for(int i = 0;i < row;++i){
        if(dict.find(s.substr(i,row - i)) != dict.end()){
            if(wb_r(i,s,dict))
                return true;
        }
    }
    return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
    return wb_r(s.size(),s,dict);
}

No comments:

Post a Comment