LeetCode - Longest SubString without repeating characters_003
2015-08-22 13:17
405 查看
首先用了时间复杂度为O(n^2)的方法,耗时比较长,花了216ms(好忧伤,自己首先想到的方法总是很耗时间。。。。)
class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> ivec; for (int i = 0; i != s.size(); ++i) { string exist; int count = 0; for (int j = i; j != s.size(); ++j) { if (exist.find(s[j]) == string::npos) { ++count; exist.insert(exist.end(), s[j]); } else { break; } } ivec.push_back(count); } int max = 0; for(vector<int>::const_iterator ite = ivec.begin();ite != ivec.end(); ++ite) { if(max < *ite) max = *ite; } return max; } };然后看了下别人的解法,时间复杂度是O(N),耗时16ms;解法就是找两个标记位,begin,end,一旦end指向的字符已经在前面出现过,就应该将begin和end同时往后移动一位,比如fdabcabc,最开始begin=0,直到end加到5,发现a字符重复,那么下一循环begin应该为3,end为6
class Solution { public: int lengthOfLongestSubstring(string s) { int length = s.size(); bool exist[128] = { false };//ASCII字符一共128种 int begin = 0, end = 0; int maxlen = 0; while(end < length) { if (exist[s[end]]) { maxlen = max(maxlen, end - begin); while (s[begin] != s[end]) { exist[s[begin]] = false; ++begin; } ++begin; ++end; } else { exist[s[end]] = true; ++end; } } maxlen = max(maxlen, end - begin);//这一步别忘了 return maxlen; } };
相关文章推荐
- WordPress For SAE进入后台
- MvvmLight ToolKit 教程
- 查找出现次数超过一半的数
- 代理IP抓取
- crontab每月最后一天执行
- rdlc报告vs2008编辑正常,在vs2012在对错误的编辑
- 谷歌Chrome浏览器64位在Win10预览版10525中将修复崩溃
- UVA 11992 - Fast Matrix Operations(段树)
- 洛谷1422 小玉家的电费
- 栈-迷宫求解路径问题
- XML认识
- 漫步Unity3D(三)
- C#在C++编写的DLL中注册函数并回调
- 周赛 大数找规律
- 双关键字快排
- 游戏摄像头漫游——3维坐标变换
- asp.net给DropDownList添加ToolTip(title)属性
- Codeforces Round #313 (Div. 2) C. Gerald's Hexagon
- 广度优先搜索和深度优先搜索
- shell网络管理