3. Longest Substring Without Repeating Characters

양성준·2025년 4월 29일

코딩테스트

목록 보기
37/102

문제

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

풀이

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int lt = 0;
        int answer = 0;
        Map<Character, Integer> map = new HashMap<>();
        

        for(int rt = 0; rt < s.length(); rt++) {
            map.put(s.charAt(rt), map.getOrDefault(s.charAt(rt), 0) + 1);
            while(map.get(s.charAt(rt)) > 1) {
                map.put(s.charAt(lt), map.get(s.charAt(lt)) - 1);
                lt++;
            }
            answer = Math.max(answer, rt - lt + 1);
        }

        return answer;
        
    }
}
  • rt를 이동시켜가며 s.charAt(rt)를 카운팅
  • s.charAt(rt)가 1보다 크다면, 조건을 만족하지 않으므로 lt를 땡겨가며 카운팅 감소
profile
백엔드 개발자

0개의 댓글