请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof
解答:
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0;
int right = 0;
int max = 0;
char[] c1 = s.toCharArray();
//维护一个HashMap存储着以当前字母结尾的子串所包含的独特字母的位置
Map<Character, Integer> map = new HashMap<>();
for (int i=0; i<c1.length; i++){
right = i;
if (map.containsKey(c1[i])){
int temp = map.get(c1[i]);
if (temp >= left && temp <= right){
left = temp + 1;
}
}
map.put(c1[i], i);
max = Math.max(right - left + 1, max);
}
return max;
}
}