[Leet code] Longest Substring without Repeating Characters (java)

백승호·2021년 3월 30일
0

알고리즘공부

목록 보기
3/6

문제

코드

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0; // index of s
        int j = 0; // index of current loop
        int maxLength = 0;
        HashSet<Character> stringSet = new HashSet<>();
        while (j < s.length())
        {
            if (i > j)
                break ;
            if (!stringSet.contains(s.charAt(j))) 
            {
                stringSet.add(s.charAt(j++));
                maxLength = Math.max(maxLength, j - i);
            }
            else
                stringSet.remove(s.charAt(i++));
        }
        
        return maxLength;
    }
}

해설

주어진 문자열 s 에서 중복되는 문자없이 만들수있는 가장 긴 substring의 길이를 구하는 문제이다.
한글자씩 s의 문자를 섭스트링에 담아주는데 담기전에 해당 문자가 섭스트링안에 존재하는지 보고, 존재하지 않는다면 넣고 존재한다면 섭스트링의 맨앞 문자를 없애준다. 루프를 돌면서 최대 길이를 갱신해준다

HashSet: Set인터페이스의 구현 클래스. 객체를 중복해서 저장할 수 없고 하나의 null 값만 저장가능하며 저장 순서가 유지되지 않는다. 중복을 걸러내는 과정으로, 객체를 저장하기 전에 먼저 객체의 hashCode()메소드를 호출해서 해시 코드를 얻어낸 다음 저장되어 있는 객체들의 해시 코드와 비교한뒤 같은 해시 코드가 있다면 다시 equals()메소드로 두 객체를 비교해서 true가 나오면 동일한 객체로 판단하고 중복 저장을 하지 않는다.

add(), remove(), clear(), size(), contains() 메소드가 있다

참고: https://limdongjin.github.io/problemsolving/Longest-Substring-Without-Repeating-Characters.html#%E1%84%86%E1%85%AE%E1%86%AB%E1%84%8C%E1%85%A6-%E1%84%8B%E1%85%B5%E1%84%92%E1%85%A2

https://coding-factory.tistory.com/554

profile
삽질하는 개발자 지망생

0개의 댓글