給定一個(gè)字符串似嗤,請(qǐng)你找出其中不含有重復(fù)字符的?最長(zhǎng)子串?的長(zhǎng)度。
示例?1:
輸入: "abcabcbb"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "abc"届宠,所以其長(zhǎng)度為 3烁落。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "b",所以其長(zhǎng)度為 1豌注。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是?"wke"伤塌,所以其長(zhǎng)度為 3。
?? ? 請(qǐng)注意轧铁,你的答案必須是 子串 的長(zhǎng)度每聪,"pwke"?是一個(gè)子序列,不是子串齿风。
import java.util.HashSet;
class LongestNoRepeatString {
? ? public static void main(String[] args) {
? ? ? ? System.out.println("abcabcbb : " + lengthOfLongestSubstring("abcabcbb"));
? ? ? ? System.out.println("bbbbb : " + lengthOfLongestSubstring("bbbbb"));
? ? ? ? System.out.println("pwwkew : " + lengthOfLongestSubstring("pwwkew"));
? ? }
? ? public static int lengthOfLongestSubstring(String s) {
? ? ? ? HashSet<Character> hashset = new HashSet<>();
? ? ? ? char[] ss = s.toCharArray();
? ? ? ? int res = 0;
? ? ? ? int l = 0, r = -1;
? ? ? ? while(l < ss.length){
? ? ? ? ? ? res = Math.max(res, r - l + 1);
? ? ? ? ? ? if( r + 1 < ss.length && !hashset.contains(ss[r+1])){
? ? ? ? ? ? ? ? hashset.add(ss[++r]);
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? hashset.remove(ss[l++]);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return res;
? ? }
}