LeetCode 3. Longest Substring Without Repeating Characters 滑动窗口
来源:互联网 发布:福岛 知乎 编辑:程序博客网 时间:2024/05/28 09:33
一、题目
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be asubstring,"pwke"
is asubsequence and not a substring.
题意:给定一个字符串,找出不重复字母连续最长子串的长度。
注意:一旦遇到字符串的题,一定要敏感,字符集的范围,字母?数字+字母?ASCII?
查找重复字符还需要考虑大小的区别。
思路:和209类似采用滑动窗口的思路。在[l...r]区间中表示不重复的字符集,为了扩大当前的字符集,加载一位新的元素时要判断新元素是否在[l...r]中,若不在扩大r+1,若在就将左边界l减至重复元素之后。在此期间不断更新维护字符区间的长度。
如何判断新的元素是否在字符集区间呢?遍历查找?find?这里有个小技巧,查表
预定义一个256大小的数组来维护字符集区间内元素出现的频率freq[256]初始为0,当加入1个元素对应的元素下标+1,当从字符集中删除一个元素对应删除元素下标需要-1,最终通过查表来看该元素是否在字符集空间中。
//时间复杂度:O(n)//空间复杂度:O(256)class Solution {public: int lengthOfLongestSubstring(string s) { int l = 0,r = -1; //初始状态[left...right]设置为无效 int res = 0; //因为是找最大子串,初始值为0 int freq[256]={0}; while(l<s.size()/*只要l还能取值就继续*/) { if(r+1<s.size()&&(freq[s[r+1]]==0)) //先去看r+1是否有重复 { r++; //未重复扩大字符集区间 freq[s[r]]++; //同时对应元素的访问频率置1 } else { //这里是对s[l]的频率进行--,是为了不断的移动至重复元素之后 freq[s[l]]--; //新元素和字符集区间中元素重复,最左侧元素频率减为0,直到l移动至重复元素之后 l++; } res = max(res,r-l+1); //不断更新最长字符集长度 } return res; }};
- LeetCode 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
- LeetCode --- 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
- [Leetcode]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
- LeetCode-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
- (Leetcode)3. Longest Substring Without Repeating Characters
- JAVA集合框架——Iterator
- Linux生成密钥
- java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this a
- 分数加减法
- [P2472]蜥蜴
- LeetCode 3. Longest Substring Without Repeating Characters 滑动窗口
- 离开工具自己手写一个servlet
- 深入理解java异常处理机制
- 聚类系列-Affinity Propagation
- 欢迎使用CSDN-markdown编辑器
- 并查集详解 (转)
- 网络性能测试工具iperf详细使用图文教程
- 实验5-运用数组拆分奇偶数
- c++上机实验报告6:矩阵求和