1- 思路
滑动窗口
- 借助
HashSet
来实现判重 - 通过指针
i
和 right
指针实现一个滑动窗口
2- 实现
⭐3. 无重复字符的最长子串——题解思路
class Solution {public int lengthOfLongestSubstring(String s) {HashSet<Character> hs = new HashSet<>();int res = 0;int right = 0;for(int i = 0 ; i < s.length();i++){if (i != 0) {hs.remove(s.charAt(i - 1));}while (right < s.length() && !hs.contains(s.charAt(right))) {hs.add(s.charAt(right));right++;}res = Math.max(res, hs.size());}return res;}
}
3- ACM 实现
public class noDuplicate {private static int nonDuplicate(String s){HashSet<Character> hs = new HashSet<>();int res = 0;int right = 0;for(int i = 0 ; i < s.length();i++){if(i>0){hs.remove(s.charAt(i-1));}while(right<s.length() && !hs.contains(s.charAt(right))){hs.add(s.charAt(right));right++;}res = Math.max(res,hs.size());}return res;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入字符串");String s = sc.nextLine();System.out.println("结果是"+nonDuplicate(s));}
}