Leetcode刷题35-3.无重复字符的最长子串(C++)
2019-03-25 19:30
483 查看
题目来源:链接: [https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/].
3.无重复字符的最长子串
1.问题描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例1:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例2:
输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
2.我的解决方案
受打击了,这题我木有做出来,我们直接上大神的 代码吧。。。
3.大神们的解决方案
别问怎么做的,问就很帅,哈哈哈
方法1:
class Solution { public: int lengthOfLongestSubstring(string s) { map<char,int> m;//map<character,index> int maxLen = 0; int start = 0; for(int i=0;i<s.size();i++) { if(m.count(s[i])>0) { start = max(start,m[s[i]]+1); //加max的原因:start只能往前走,不能往后退。 } maxLen = max(maxLen,i-start+1);//本题求最大,故加max。 m[s[i]] = i; //无论是否重复,都更新字符对应的下标为:当前字符串最新出现该字符的下标。 } return maxLen; } };
方法2:
class Solution { public: int lengthOfLongestSubstring(string s) { int maxLength = 0; map<char, int> m; int len = 0; for (int i = 0; i < s.size(); i ++) { if (m.count(s[i]) == 0) { len += 1; m[s[i]] = i; } else { len = 0; i = m[s[i]]; m.clear(); } if (maxLength < len) { maxLength = len; } } return maxLength; } };
4.我的收获
继续努力。。。
自己的路还有很长。。。
2019/3/25 胡云层 于南京 35
相关文章推荐
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- 【Leetcode一刷】3.无重复字符的最长子串
- Leetcode:395至少有K个重复字符的最长子串(C++)
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串 Python
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- [Leetcode] 3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- LeetCode题解(python)-3.无重复字符的最长子串
- Leetcode 3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- [C++]LeetCode 3: Longest Substring Without Repeating Characters(最长不重复子串)
- LeetCode给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
- LeetCode 3 无重复字符的最长子串(哈希表或数组)
- [LeetCode]3. Longest Substring Without Repeating Characters寻找最长无重复字符的子串
- 求字符串的最长无重复字符子串(C++)
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】