Leetcode(C++)——3. 无重复字符的最长子串
2019-02-26 21:30
459 查看
3. 无重复字符的最长子串
①题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
②示例
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
③解法
方法一:滑动窗口法遍历字符串每一个元素,判断可以延伸的最大长度,选择最大的长度。
class Solution { public: int lengthOfLongestSubstring(string s) { int max_len = 0; for(int i = 0; i < s.length(); i++) { map<char, int> mymap; int tmp_len = 0; for(int j = i; j < s.length(); j++) { if(mymap.find(s[j]) != mymap.end()) { break; } else { mymap[s[j]] = 1; tmp_len++; } } max_len = max_len > tmp_len ? max_len : tmp_len; if(i + max_len >= s.length()) { break; } } return max_len; } };
Leetcode的测试结果:
不需要每次只移动一位,移动到重复字符出现的位置。
class Solution { public: int lengthOfLongestSubstring(string s) { int n = s.length(), ans = 0; map<char, int> map; for(int i = 0, j = 0; j < n; j++) { if(map.find(s[j]) != map.end()) { i = max(map[s[j]], i); } ans = max(ans, j - i + 1); map[s[j]] = j + 1; } return ans; } };
Leetcode的测试结果:
和方法二类似,不同之处方法二用了map,方法三利用了ASCII数组。
class Solution { public: int lengthOfLongestSubstring(string s) { int n = s.length(), ans = 0; int index[128]; for(int i = 0, j = 0; j < n; j++) { i = max(index[s[j]], i); ans = max(ans, j - i + 1); index[s[j]] = j + 1; } return ans; } };
Leetcode的测试结果:
④总结
网上看了很多方法,不够还是理解不深,自己重新敲一下代码领会一下!
相关文章推荐
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- LeetCode题目C++实现:3. 无重复字符的最长子串
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- LeetCode 3. 无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- Leetcode 3. 无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- LeetCode3. 无重复字符的最长子串(Java)
- leetcode 3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串(Java 版)
- leetcode 3.无重复字符的最长子串
- 【Leetcode一刷】3.无重复字符的最长子串
- LeetCode题解(python)-3.无重复字符的最长子串
- Leetcode:395至少有K个重复字符的最长子串(C++)