LeetCode()Substring with Concatenation of All Words 为什么我的超时呢?找不到原因了!!!
2015-11-24 23:04
344 查看
超时代码
这个和我的没有什么区别吧?为什么就可以呢?
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { map<string,int> coll; for(auto i:words) coll[i]++; vector<int> res; int len=words[0].size(),sum=words.size(); for(int k=0;k<=s.length()-len*sum;k++) if(check(s,k,len,sum,coll)) res.push_back(k); return res; } bool check(string s,int start,int len,int sum,map<string,int> coll) { for(int i=start;i<=s.length()-len && sum!=0;i+=len) { string str=s.substr(i,len); auto d=coll.find(str); if(coll[str]>0 && d != coll.end()) { coll[str]--; sum--; } else return false; } if(sum==0) return true; else return false; } };
这个和我的没有什么区别吧?为什么就可以呢?
class Solution { private: int wordLen; public: vector<int> findSubstring(string S, vector<string> &L) { unordered_map<string, int>wordTimes; for(int i = 0; i < L.size(); i++) wordTimes[L[i]]++; wordLen = L[0].size(); vector<int> res; for(int i = 0; i <= (int)(S.size()-L.size()*wordLen); i++) if(helper(S, i, wordTimes, L.size())) res.push_back(i); return res; } //判断子串s[index...]的前段是否能由L中的单词组合而成 bool helper(const string &s, int index, unordered_map<string, int>wordTimes, int wordNum) { for(int i = index; wordNum != 0 && i <= (int)s.size()-wordLen; i+=wordLen) { string word = s.substr(i, wordLen); auto ite = wordTimes.find(word); if(ite != wordTimes.end() && ite->second > 0) {ite->second--; wordNum--;} else return false; } if(wordNum == 0)return true; else return false; } };
相关文章推荐
- !
- LintCode:旋转链表
- 关于addSpriteFramesWithFile读取失败
- 求两个并联电阻的值
- 如何在datetime.strptime中添加时区
- qtcreator minggw 支持c++11
- finereport的服务器负载均衡部署--tomcat
- http://macrochen.iteye.com/blog/1414568
- LintCode:旋转图像
- 开源的DevOps开发工具箱
- Matlab 实现矩阵的满秩分解(最大秩分解)
- 错误处理
- 第二百三十六天 how can I 坚持
- odoo worker 异常Exception("bus.Bus unavailable")
- Java FP: Java中函数式编程的Map和Fold(Reduce)
- 对数据库中完整性概述的认识
- Coderforce #332 D. Spongebob and Squares
- 窗体运行前,检查是否互斥
- 原生JS练习计算器和banner条滚动效果
- lua学习03——table