Word Break II

来源:互联网 发布:福建游龙网络 编辑:程序博客网 时间:2024/06/12 09:25

题目:

链接


解答:

用mark[]记录每次分割位置。

代码:

class Solution {public:int flag = 0;vector<string> result;string last;vector<string> wordBreak(string s, unordered_set<string> &dict) {int a[26];last = s;for (int i = 0; i < 26; i++)a[i] = 0;for (int i = 0; i < s.length(); i++)a[s[i] - 'a'] = 1;for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++){for (int j = 0; j < it->length(); j++){string temp = *it;a[temp[j] - 'a'] = 0;}}int temp = 0;for (int i = 0; i < 26; i++){temp += a[i];}if (temp > 0)return result;int mark[100];search(s, dict, mark, 0);return result;}void search(string s, unordered_set<string> &dict, int mark[], int len){if (s == ""){flag = 1;string ts1 = "";string ts2 = last;for (int i = 0; i < len; i++){ts1 = ts1 + " " + ts2.substr(0, mark[i]);ts2 = ts2.substr(mark[i], ts2.length() - mark[i]);}ts1 = ts1.substr(1, ts2.length() - 1);result.push_back(ts1);}else{for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++){string tempstr = s.substr(0, it->length());if (tempstr == *it){tempstr = s.substr(it->length(), s.length() - it->length());mark[len] = it->length();search(tempstr, dict, mark, len+1);}}}}};


0 0
原创粉丝点击