LeetCode 3. Longest Substring Without Repeating Characters
Woodyiiiiiii opened this issue · comments
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.
利用滑动窗口法。
定义两个指针代表滑动窗口,两个指针的距离代表定义的字符串长度,并且创建一个HashSet存储字符以便判断字符重复。遍历字符串,如果字符不存在于窗口中,则存入HashSet中,右指针加一;如果存在,左指针加一,并且从HashSet中删除该字符。每次计算更新最长的长度。
注意,如果字符串是“abcdbd”,字符‘b’重复,则左指针加一,把字符'a'剔除了,同时在HashSet中删除了‘a’字符,因为题目要求的是substring,是continuous连续的,所以左指针移动直至删除最先存入的字符‘b’才可。HashSet存的是理想的无重复字符的字符串,窗口长度代表的是HashSet的大小。
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()== 0)
return 0;
HashSet<Character> set = new HashSet<Character>();
int i =0, j = 0;
int maxLen = 0;
while (i < s.length() && j < s.length())
{
if(!set.contains(s.charAt(i))) {
set.add(s.charAt(i));
i++;
maxLen = Math.max(maxLen, i-j);
}
else {
set.remove(s.charAt(j));
j++;
}
}
return maxLen;
}
}
参考资料:
func lengthOfLongestSubstring(s string) int {
var l = 0
var r = 0
n := len(s)
res := 0
charMap := make(map[byte]int)
for r < n {
c := s[r]
if _, ok := charMap[c]; ok {
for l <= r {
if s[l] == c {
l++
break
}
delete(charMap, s[l])
l++
}
}
res = int(math.Max(float64(res), float64(r-l+1)))
r++
charMap[c]++
}
return res
}