LeetCode3. 无重复字符的最长子串
【LeetCode3】3.无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例一:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例二:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例三:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
class Solution {
// 双指针
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0)
return 0;
HashMap<Character, Integer> map = new HashMap<>();
int i=0, j=0;
int res = 0;
while(j < s.length()){
char ch = s.charAt(j);
if(map.containsKey(ch)){
i = Math.max(i, map.get(ch)+1);
}
res = Math.max(res, j-i+1);
map.put(ch, j);
j++;
}
return res;
}
}
查看18道真题和解析