Substring with Concatenation of All Words
来源:互联网 发布:网络服务费增值税税率 编辑:程序博客网 时间:2024/04/28 17:13
嗯先贴一个最初的实现,思路是对的,但是编码能力太差,写出来有问题。
class Solution {public: vector<int> findSubstring(string S, vector<string> &L) { int llen = L[0].length(); vector<int> res; if (S == "") return res; vector<bool> used; for (int i = 0; i < L.size(); ++i) used.push_back(false); for (int i = 0; i < S.length(); ++i) { for (int j = 0; j < L.size(); ++j) used[j] = false; int j; for (j = 0; j < L.size() && i + (j + 1) * llen <= S.length(); ++j) { if (!isValid(S.substr(i + j * llen, llen), L, used)) { i = i + j * llen; break; } } if (j == L.size()) res.push_back(i); } } bool isValid(string s, vector<string> &L, vector<bool> &used) { int index = -1; for (int i = 0; i < L.size(); ++i) { if (s == L[i] && used[i] == false) index = i; } if (index == -1) return false; used[index] = true; return true; }};
目前的结论是,我之前的思路是正确的,使用map可以大大加快速度。并且,由于STL效率差,因此能不重复做的工作坚决不重复做。
class Solution {public:vector<int> findSubstring(string S, vector<string> &L) {vector<int> res;if (S == "")return res;map<string, int> words;map<string, int> curStr;for (int i = 0; i < L.size(); ++i)++words[L[i]];int len = L.size() * L[0].length();for (int i = 0; i + len <= S.length(); ++i) {if (isValid(S.substr(i, len), L, words, curStr))res.push_back(i);}return res;}bool isValid(string s, vector<string> &L, map<string, int> &words, map<string, int> &curStr) {curStr.clear();int wordLen = L[0].length();for (int i = 0; i + wordLen <= s.length(); i += wordLen) {string sub = s.substr(i, wordLen);if (words.find(sub) == words.end())return false;++curStr[sub];if (curStr[sub] > words[sub])return false;}return true;}};
http://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/
0 0
- LeetCode: Substring with Concatenation of All Words
- LeetCode : Substring with Concatenation of All Words
- LeetCode29: Substring with Concatenation of All Words
- [Leetcode] Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- 26 - Substring with Concatenation of All Words
- LeetCode:Substring with Concatenation of All Words
- Leetcode: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words
- 单例模式
- 移动开发者的自学宝典:十大在线编程学习网站
- WCF服务IIS寄宿
- JMail的SSL以及非SSL发送邮件
- 数据结构 单链表的就地转置
- Substring with Concatenation of All Words
- SQL语句(创建书库,创建建表,写入注释,获取注释)
- 读《富爸爸穷爸爸》有感
- 数据结构 静态链表的建立
- fedora 19 安装中文语言包
- 数据结构 静态链表的插入与删除
- C#中的异步调用及异步设计模式(一)
- java.util.ConcurrentModificationException解决办法
- 数据结构 静态链表的应用