[M] 3. Longest Substring Without Repeating Characters

YJ·7일 전

leetcode

목록 보기
74/100

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

문제

중복 문자 없는 최장 substring 의 길이

답안

public int lengthOfLongestSubstring(String s) {
	Map<Character, Integer> map = new HashMap<>();
	int right = 0;
	int maxLength = 0;
	for (int left = 0; left < s.length(); left++) {
		while (right < s.length() && map.getOrDefault(s.charAt(right), 0) == 0) {
			map.put(s.charAt(right), 1);
			right++;
		}
		maxLength = Math.max(maxLength, right - left);
		map.put(s.charAt(left), map.get(s.charAt(left)) - 1);
	}
	return maxLength;
}

메모

Sliding window는 보통 right 을 이동한다구 하네여 기억~~

public int lengthOfLongestSubstring(String s) {
	Map<Character, Integer> lastSeen = new HashMap<>();
	int left = 0;
	int maxLength = 0;

	for (int right = 0; right < s.length(); right++) {
		char c = s.charAt(right);
		if (lastSeen.containsKey(c)) {
			left = Math.max(left, lastSeen.get(c) + 1);
		}
		lastSeen.put(c, right);
		maxLength = Math.max(maxLength, right - left + 1);
	}
	return maxLength;
}
  1. 새로 들어갈 (맨 오른쪽) 글자 확인 후,
  2. 이미 있는 글자면 left 를 중복 문자 있었던 index + 1 로 옮겨준다! (문자가 마지막으로 등장한 index 를 저장..) left 가 뒤로 이동 못하게 막아주기도 해야 함
  3. 새로 들어갈 글자의 index 까지도 저장하고
  4. 최대 길이 측정해준다.
    while 로 안 돌려도 되는군
profile
Hello

0개의 댓글