Sliding Window Algorithm (leetcode)

이기현·2020년 8월 13일
0

코딩테스트 준비

목록 보기
14/20

문제는
Given a string, find the length of the longest substring without repeating characters.

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

이 문제를 풀 때에는 sliding window라는 알고리즘을 풀면 쉽게 풀 수 있다.

슬라이딩 윈도우 알고리즘은
윈도우 즉 일정한 범위(window)를 가지고 이동(sliding)하는 것을 말한다.

잘 설명이 되어있는 블로그의 글을 가져와보았다.

이 문제를 풀 때에도 leftindex와 rightindex를 활용해서 문제를 풀었다.

class Solution {
    public int lengthOfLongestSubstring(String s) {

		if(s.equals(""))
			return 0;
		if(s.trim().isEmpty())
			return 1;
		HashMap<Character,Integer> map = new HashMap<Character,Integer>();

		int rightIdx = 0; 
		int leftIdx = 0;
		int max = 0;
		
		while(rightIdx < s.length()) {
			if(!map.containsKey(s.charAt(rightIdx))) {
				map.put(s.charAt(rightIdx), rightIdx++);
				max = Math.max(max, rightIdx - leftIdx );
			}
			else {
				map.remove(s.charAt(leftIdx++));
			}
		}
		return max;
	}
}
profile
실력을 쌓아가는 하루하루

0개의 댓글