leetcoode 3.Longest Substring Without Repeating Characters
来源:互联网 发布:android 创建数据库 编辑:程序博客网 时间:2024/06/08 02:23
题意
找各个字符都不同的最长子串。
题解
使用STL自带的hash容器map。枚举每个起始位置开始的子串需要O(n^2),会超时。使用尺取法在O(n)时间内解决。
代码
class Solution {public: int lengthOfLongestSubstring(string s) { int len = s.length(); if (len == 1) return 1; int maxlen = 0; int i = 0; int j = i + 1; map<char, int> dict; // means (character : postion) dict[s[i]] = i; map<char, int>::iterator eit = dict.end(); while (i < len) { while (j < len && dict.find(s[j]) == eit ) // find a character that has been in substring { dict[s[j]] = j; //not found j++; } if (j == len) { maxlen = max(maxlen, j - i); break; } else { maxlen = max(maxlen, j - i); int nexti = dict[s[j]]; // old pos of s[j] while (i <= nexti) // update dict: delete ele from i to nexti dict.erase(s[i++]); // or implicit delete: dict[s[i++]] = -1; dict[s[j]] = j; // update s[j] into new pos j++; } } return maxlen; }};
0 0
- leetcoode 3.Longest Substring Without Repeating Characters
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【机房系统个人重构】跌跌撞撞也好,开始前进!
- ORA-00314;ORA-00312
- android 网络连接
- 如何用 OS X 的 Xcode 写C语言程序
- 小游戏 1to 50
- leetcoode 3.Longest Substring Without Repeating Characters
- 监听RecyclerView滑动到末端
- 初识 C#
- leetcode83题 题解 翻译 C语言版 Python版
- Binding MySql DataSources in Jboss EAP 7.0
- “Genymotion运行Android模拟器一直卡在开机界面”的解决办法
- 于是就来到第三节_(:зゝ∠)_运算符重载
- html5
- 理解A*寻路算法具体过程