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"
.
第一种方法:递归(超时)Time Limit Exceeded
思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配
Last executed input: | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] |
bool wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once. if(s.length() < 1) return true; bool flag = false; for(int i = 1; i <= s.length(); i++) { string tmpstr = s.substr(0,i); unordered_set<string>::iterator it = dict.find(tmpstr); if(it != dict.end()) { if(tmpstr.length() == s.length())return true; flag = wordBreak(s.substr(i),dict); } if(flag)return true; } return false; }
第二种方法:dpAccepted
思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配,在找后缀是否匹配时添加了记忆功能。
bool wordBreakHelper(string s, unordered_set<string> &dict,set<string> &unmatch) { if(s.length() < 1) return true; bool flag = false; for(int i = 1; i <= s.length(); i++) { string prefixstr = s.substr(0,i); unordered_set<string>::iterator it = dict.find(prefixstr); if(it != dict.end()) { string suffixstr = s.substr(i); set<string>::iterator its = unmatch.find(suffixstr); if(its != unmatch.end())continue; else{ flag = wordBreakHelper(suffixstr,dict,unmatch); if(flag) return true; else unmatch.insert(suffixstr); } } } return false; } bool wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once. int len = s.length(); if(len < 1) return true; set<string> unmatch; return wordBreakHelper(s,dict,unmatch); }
dp改进:dict中的单词有的长有的短,当prefixstr串小于最短串时就不匹配了,当prefixstr串大于最长的串时也不用匹配了。多谢@阿桂爱清净
bool wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched,int mn,int mx) { if(s.size() < 1) return true; int i = mx < s.length() ? mx : s.length(); for(; i >= mn ; i--) { string preffixstr = s.substr(0,i); if(dict.find(preffixstr) != dict.end()){ string suffixstr = s.substr(i); if(unmatched.find(suffixstr) != unmatched.end()) continue; else if(wordBreakHelper(suffixstr, dict, unmatched,mn,mx)) return true; else unmatched.insert(suffixstr); } } return false; } bool wordBreak(string s, unordered_set<string> &dict) { // Note: The Solution object is instantiated only once. if(s.length() < 1) return true; if(dict.empty()) return false; unordered_set<string>::iterator it = dict.begin(); int maxlen=(*it).length(), minlen=(*it).length(); for(it++; it != dict.end(); it++) if((*it).length() > maxlen) maxlen = (*it).length(); else if((*it).length() < minlen) minlen = (*it).length(); set<string> unmatched; return wordBreakHelper(s,dict,unmatched,minlen,maxlen); }