Leetcode3-无重复字符的最长子串
2019-02-16 16:26
281 查看
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
注意:子串一定是连续的一段。子序列不一定是连续的一段,但下标要求是递增的
示例一
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例二
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例三
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
思路
可以用双指针扫描算法。
指针 j 向后移一位, 同时将哈希表中 s[j] 的计数加1: hash[s[j]]++;
假设 j 移动前的区间 [i,j] 中没有重复字符,则 j 移动后,只有 s[j] 可能出现2次。因此我们不断向后移动 i,直至区间 [i,j]中 s[j] 的个数等于1为止;
代码
class Solution { public: int lengthOfLongestSubstring(string s){ map<char,int>hash; int res=0; for(int i=0,j=0;j<s.length();j++) { if(++ hash[s[j]]>1) { while(i<j) { hash[s[i]]--; i++; if(hash[s[j]]==1)break; } } res=max(res,j-i+1); } return res; } };
相关文章推荐
- Leetcode:395至少有K个重复字符的最长子串(C++)
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- 无重复字符的最长子串 - LeetCode
- leetcode 3. 无重复字符的最长子串(Java 版)
- leetcode之3. 无重复字符的最长子串python实现
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- leetcode 3:无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode 3. 无重复字符的最长子串
- [LeetCode] Longest Substring Without Repeating Characters 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- 【leetcode】第3题:求最长不重复(字符不重复)的子串的长度
- LeetCode 无重复字符的最长子串
- Leetcode(C++)——3. 无重复字符的最长子串
- leetcode-最长无重复字符的子串
- LeetCode-3-无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串