[LeetCode] Longest Substring Without Repeating Characters

urzi·2022년 6월 30일
0

PS

목록 보기
27/36

문제

https://leetcode.com/problems/longest-substring-without-repeating-characters/

알고리즘

문자열

풀이

반복문자가 없는 가장 긴 문자열의 길이

인덱스 두개로 풀어나간다.
j는 항상 i보다 +1을 해야 중복문자를 걸러낼 수 있다.
i와 j가 다를떄에만 정답 HashSet에 넣어야 역시 중복을 걸러낼 수 있다.

코드

class Solution {
    public int lengthOfLongestSubstring(String s) {

        if (s.length() == 0) {
            return 0;
        }

        HashSet<Character> compare = new HashSet<>();
        int answer = 1;
        int i = 0;
        int j = 1;

        while (i < s.length() && j < s.length()) {
            if (!compare.contains(s.charAt(j)) && s.charAt(i) != s.charAt(j)) {
                compare.add(s.charAt(j));
                answer = Math.max(answer, j - i + 1);
                j++;
            } else {
                compare = new HashSet<>();
                i++;
                j = i + 1;
            }
        }

        return answer;
    }
}
profile
Back-end Developer

0개의 댓글