LeetCode 3. 无重复字符的最长子串
2019-03-25 20:25
204 查看
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke"是一个子序列,不是子串。
问题分析
记录每一个字符最后一次出现的位置,这样才能使得在更新左边界m时,在哈希表中找到的是该字符最后一次出现的位置。左边界只能向右移动,不能向左移动,所以在更新左边界m时需要判断一下。遍历每个字符时,当前长度为当前位置减去m。
代码实现
[code]class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char,int> umap; int m = -1; int len = 0; int maxlen = 0; for(int i=0;i<s.length();i++){ if(umap.count(s[i])>0 && umap[s[i]]>m) m = umap[s[i]]; umap[s[i]] = i; len = i - m; if(len>maxlen) maxlen = len; } return maxlen; } };
相关文章推荐
- [Leetcode] 3.无重复字符的最长子串
- 【Leetcode一刷】3.无重复字符的最长子串
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- LeetCode题目C++实现:3. 无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串(Java 版)
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- Leetcode 3. 无重复字符的最长子串
- LeetCode题解(python)-3.无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(Java)
- leetcode 3. 无重复字符的最长子串
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode 3. 无重复字符的最长子串 Python
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)