问题描述
Given a string, find the length of the longest substring without repeating characters.
例子
Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: 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.
方法
保留一个将字符串中的字符存储为键并将其位置存储为值的hashmap,并保留两个定义最大子字符串的指针。移动右指针以浏览字符串,同时更新hashmap。如果字符已经在hashmap中,则将左指针移到最后找到的相同字符的右边。请注意,两个指针只能向前移动。
** Solution Java ** ** 7ms, 79.25% ** ** 41.9MB, 5.20% ** class Solution { public int lengthOfLongestSubstring(String s) { if (s.length() <= 1) return s.length(); Map<Character, Integer> map = new HashMap<>(); int cur = 0, max = 0; for (int i = 0; i < s.length(); ++i) { if (map.containsKey(s.charAt(i))) { cur = Math.max(cur, map.get(s.charAt(i)) + 1); } map.put(s.charAt(i), i); max = Math.max(max, i - cur + 1); } return max; } }
** Solution Python3 ** ** 56ms, beats 76.40% ** ** 13MB, beats 99.49% ** class Solution: def lengthOfLongestSubstring(self, s) : cur = maxLength = 0 usedChar = {} for index, char in enumerate(s) : if char in usedChar and cur <= usedChar[char]: cur = usedChar[char] + 1 else: maxLength = max(maxLength, index - cur + 1) usedChar[char] = index return maxLength
来源:https://www.cnblogs.com/willwuss/p/12275316.html