1.题目描述
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.因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,”pwke” 是一个子序列,不是子串。
乍一看这道题目的时候,直接哇的一声,因为今年投大厂实习的时候,在线笔试碰到这道题。日拱一卒!加油!
附上一段LeetCode评论:
By the way, I was offered a job at Google, and I work there as a SWE now. Guys, practice leet code oj online, it really really helps!
2.Solutions
作者思路:使用一个HashMap存储字符串:key为字符,value为位置。并且使用两个指针i、j用来定义最大子串。使用指针i遍历整个数组,同时更新hashmap:如果字符出现在hashmap中,则移动指针j到上次找到的同样字符串加1的位置。注意:两个指针只能往前移动。
1 | public static int lengthOfLongestSubstring(String s) { |