Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 104sconsists of English letters, digits, symbols and spaces.
思路
- 定义一个哈希表存放字符及其出现的位置;
- 定义 i, j 分别表示不重复子串的开始位置和结束位置;
- j 向后遍历,若遇到与
[i, j]区间内字符相同的元素,更新 i 的值,此时[i, j]区间内不存在重复字符,计算 res 的最大值。
class Solution {
public int lengthOfLongestSubstring(String s) {
int res = 0;
Map<Character, Integer> chars = new HashMap<>();
for (int i = 0, j = 0; j < s.length(); ++j) {
char c = s.charAt(j);
if (chars.containsKey(c)) {
// chars.get(c)+1 可能比 i 还小,通过 max 函数来锁住左边界
// e.g. 在"tmmzuxt"这个字符串中,遍历到最后一步时,最后一个字符't'和第一个字符't'是相等的。如果没有 max 函数,i 就会回到第一个't'的索引0处的下一个位置
i = Math.max(i, chars.get(c) + 1);
}
chars.put(c, j);
res = Math.max(res, j - i + 1);
}
return res;
}
}