LeetCode--longest-substring-without-repeating-characters
2018-01-19 22:53
323 查看
题目描述
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 of1.
分析:求最大无重复字符的子串
思路:用一个map记录各个字符的下标,首先将所有的下表初始化为-1,然后向后遍历的过程中记录当前字符的下标,并将当前字符的下标与上一个相同字符的下标做差值,即可得到它们之间无重复字符的子串。然后用Max记录更新最大子串数,并更新map存储的下标值,即从这个重复值重新开始数字符串的数(最大无重复字符子串必定在两个重复字符之间,或者是整个字符串的长度)
这种方法好像被叫做滑动窗口法
"滑动窗口"
比方说 abcabccc 当你右边扫描到abca的时候你得把第一个a删掉得到bca,
然后"窗口"继续向右滑动,每当加到一个新char的时候,左边检查有无重复的char,
然后如果没有重复的就正常添加,
有重复的话就左边扔掉一部分(从最左到重复char这段扔掉),在这个过程中记录最大窗口长度
其实和上面的思路是一样的!
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> book;
int i,Max=0,pre=-1;
for(i=0;i<s.length();i++) book[s[i]]=-1;
for(i=0;i<s.length();i++)
{
pre=max(pre,book[s[i]]);//更新map中各个字符的下标
Max=max(Max,i-pre); //保存暂时的最大无重复子串长度
book[s[i]]=i; //计算差值后继续更新
}
return Max;
}
};
相关文章推荐
- Leetcode3:Longest Substring Without Repeating Characters
- LeetCode003__Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters - LeetCode
- LeetCode题解 #3 Longest Substring Without Repeating Characters
- Leetcode Longest Substring Without Repeating Characters(最长不重复子串)
- LeetCode Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- LeetCode (3) Longest Substring Without Repeating Characters
- 算法分析与设计——LeetCode Problem.3 Longest Substring Without Repeating Characters
- 003_LeetCode_3 Longest Substring Without Repeating Characters 题解
- [LeetCode]003-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