본문 바로가기

카테고리 없음

letCode - Longest Substring Without Repeating Characters

import java.util.*;

public class algo {
    public static void main(String[] args) {
        String s = "abcabcbb";

        lengthOfLongestSubstring(s);
    }

    public static int lengthOfLongestSubstring(String s) {
        int answer = 0;

        HashMap<Character, Integer> myMap = new HashMap<>();
        for (int j = 0, i = 0; j < s.length(); j++) {
            if (myMap.containsKey(s.charAt(j))) {
                i = Math.max(myMap.get(s.charAt(j)), i);
            }
            answer = Math.max(answer, j - i + 1);
            myMap.put(s.charAt(j), j + 1);
        }

        return answer;
    }
}