|
| 1 | +package com.hyeonah.javalabs.algorithm.top50coding.stringAndArray; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by hyeoni90 on 2021-02-15 |
| 8 | + * |
| 9 | + * ex1) |
| 10 | + * input: "ccaabbb" |
| 11 | + * output: 5 (length of `aabbb`) |
| 12 | + * |
| 13 | + * ex2) |
| 14 | + * input: "eceba" |
| 15 | + * output: 3 (length of `ece`) |
| 16 | + * |
| 17 | + * keyword > |
| 18 | + * Map, Two Pointer, Math.max |
| 19 | + * (start, end 를 알아야하며, end-start 한 length 를 알아야 한다.) |
| 20 | + */ |
| 21 | +public class LongestSubstringWithAtMostTwoDistinct { |
| 22 | + |
| 23 | + public static void main(final String[] args) { |
| 24 | + final String str = "ccaabbb"; |
| 25 | + final String str1 = "eceba"; |
| 26 | + System.out.println(new LongestSubstringWithAtMostTwoDistinct().solution(str)); |
| 27 | + System.out.println(new LongestSubstringWithAtMostTwoDistinct().solution(str1)); |
| 28 | + } |
| 29 | + |
| 30 | + private int solution(final String str) { |
| 31 | + int start = 0; |
| 32 | + int count = 0; // 문자열의 문자 갯수..2 |
| 33 | + int maxLength = 0; |
| 34 | + |
| 35 | + // 문자열의 문자과 문자 갯수 |
| 36 | + final Map<Character, Integer> map = new HashMap<>(); |
| 37 | + |
| 38 | + for (int i = 0; i < str.length(); i++) { |
| 39 | + final char endChar = str.charAt(i); |
| 40 | + map.put(endChar, map.getOrDefault(endChar, 0) + 1); // cß=2, a=2, b=3 |
| 41 | + |
| 42 | + if (map.get(endChar) == 1) { |
| 43 | + count++; |
| 44 | + } |
| 45 | + |
| 46 | + // 기존에 담겨 있던 문자을 삭제한다. |
| 47 | + if (count > 2) { |
| 48 | + final char startChar = str.charAt(start); // c |
| 49 | + map.put(startChar, map.get(startChar) - 1); |
| 50 | + if (map.get(startChar) == 0) { |
| 51 | + count--; |
| 52 | + } |
| 53 | + start++; |
| 54 | + } |
| 55 | + |
| 56 | + maxLength = Math.max(maxLength, i - start + 1); |
| 57 | + } |
| 58 | + |
| 59 | + return maxLength; |
| 60 | + } |
| 61 | +} |
0 commit comments