-
[알고리즘] Longest Substring알고리즘/배열 2021. 4. 21. 11:06
Problem
- Input : ccaabbb
- Output : 5
Key Point
새로운 문자가 나오면 기존 것과 비교해서 Max 값을 구한다. (while(counter > 2))
Code
public class LongestSubMostDist { public int solution(String s) { int counter = 0, start = 0, length = 0; Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); map.put(c, map.getOrDefault(c, 0) + 1); if(map.get(c) == 1) counter++; while (counter > 2) { char startChar = s.charAt(start); map.put(startChar, map.get(startChar) - 1); if(map.get(startChar) == 0) counter--; start++; } length = Math.max(length, i - start+1); } return length; } public static void main(String[] args) { String s = "ccaabbb"; LongestSubMostDist problem = new LongestSubMostDist(); System.out.println(problem.solution(s)); } }
'알고리즘 > 배열' 카테고리의 다른 글
[알고리즘] Find Anagram Mappings (0) 2021.04.22 [알고리즘] Maximum Subarray (0) 2021.04.21 [알고리즘] Unique Email Addresses (0) 2021.04.21 [알고리즘] Move Zeroes (0) 2021.04.20 [알고리즘] Two Sum (0) 2021.04.20