(算法分析Week19)Longest Substring Without Repeating Characters 最长无重复子串 [Medium]
2018-01-20 21:10
591 查看
3.Longest Substring Without Repeating Characters 最长无重复子串 [Medium]
[题目来源https://leetcode.com/problems/longest-substring-without-repeating-characters/description/)Description
Given a string, find the length of the longest substring without repeating characters.Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
Solution
求最长无重复子串。用一个整型数组代替哈希表,然后遍历整个字符串,判断之前有没有遇到该字符。如果遇到,存储当下字符串的值,和max比较,看选哪个。然后从这个字符(第一次遇到)开始往后找。
Complexity analysis
O(n)Code
class Solution { public: int lengthOfLongestSubstring(string s) { int m[256] = {0}, res = 0, left = 0; for (int i = 0; i < s.size(); ++i) { if (m[s[i]] == 0 || m[s[i]] < left) { res = max(res, i - left + 1); } else { left = m[s[i]]; } m[s[i]] = i + 1; } return res; } };
Result
相关文章推荐
- 3 Longest Substring Without Repeating Characters(最长不重复连续子串Medium)
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- Longest Substring Without Repeating Characters 最长不重复子串
- 【LeetCode】4. Longest Substring Without Repeating Characters 最长无重复子串
- LeetCode - Longest Substring Without Repeating Characters(最长不重复子串)
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- 【LeetCode】Longest Substring Without Repeating Characters && 【九度】题目1530:最长不重复子串
- Longest Substring Without Repeating Characters (返回最长无字符重复的子串长度)
- [LeetCode] Longest Substring Without Repeating Characters 最长无重复子串
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)
- Leetcode Longest Substring Without Repeating Characters(最长不重复子串)
- (python3)最长无重复字符子串Longest Substring Without Repeating Characters
- 03 最长不重复子串Longest Substring Without Repeating Characters
- leetcode-Longest Substring Without Repeating Characters 最长不重复子串
- LeetCode | Longest Substring Without Repeating Characters(最长连续不重复子串)
- Longest Substring Without Repeating Characters,最长无重复字符子串
- Longest Substring Without Repeating Characters(最长无重复子串的长度) 回顾!略难
- LeetCode:Longest Substring Without Repeating Characters(最长不重复子串)