【LeetCode】Longest Substring Without Repeating Characters
来源:互联网 发布:mysql替换部分字符串 编辑:程序博客网 时间:2024/06/10 20:47
题目描述:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
一开始题目理解错误,或者是受前面输出子集的影响,直接取了不重复的字母数……
最开始试了下暴力枚举,O(n*n)复杂度,不出意外TLE。
然后考虑用map<char, int>来储存之前出现过的字符位置,每当出现重复字符时,将指针移回该字符上次出现的位置,map清空重新遍历,在过大数据的时候还是TLE,不过显然走的比之前远一点。
再然后考虑怎么将其优化到O(n)。再使用一个index变量来储存重复字符上次出现的位置,判定字符重复时加一个条件,即该字符上次出现的位置在index后面,这样就避免了将指针回移进行重复遍历。
代码如下:
class Solution {public:int lengthOfLongestSubstring(string s) {int count(0), index(0), res(0);unordered_map<char, int> dup;for (int i = 0; i < s.length(); i++){if (dup.count(s[i])&&dup[s[i]]>=index){index = dup[s[i]];count = i - index - 1;}dup[s[i]] = i;count++;res = std::max(res, count);}return res;}};
0 0
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- 使用github配置vim记录
- Java获取某年某周的第一天
- TimesTen重建备机操作[TimesTen运维基础]
- 同一Activity的实例被多次重复创建
- leetcode candy
- 【LeetCode】Longest Substring Without Repeating Characters
- socket.io+angular.js+express.js做个聊天应用(三)
- 我在CSDN开博了
- 纯css3实现饼状图-------Day21
- OOAD与UML笔记
- C#将dataTable类型转换为json类型
- 关于大端和小端存放的问题
- UBUNTU管理源码包
- hdu1166 敌兵布阵 线段树,单点更新