1. 程式人生 > 其它 >AtCoder題解 —— AtCoder Beginner Contest 186 —— A - Brick

AtCoder題解 —— AtCoder Beginner Contest 186 —— A - Brick

原題連結:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // 思路:
        // 類似雙指標加set集合並用
        // i 到 j 表示找的這個串
        // 這個串的字元都在set裡,
        // 如果沒有重複的,往後找並加入到 set 裡面去
        // 如果遇到重複的,set的對應值去掉
        int i = 0, j = 0, res = 0;
        int n = s.length();
        Set<Character> set = new HashSet<Character>();
        while (i < n && j < n){
            // 如果不包含則加入到set裡去
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j));
                j++;
            } else{
                set.remove(s.charAt(i));
                i++;
            }
            res = Math.max(res, j-i);
        }
        return res;
    }
}

  要點:雙指標思維+set 的運用