Longest Substring With At Most Two Distinct
Given a string s, find the length of the longest substring t that contains at most 2 distinct characters. ์ต๋ 2๊ฐ์ ๊ตฌ๋ถ๋ ์ฒ ์๋ฅผ ํฌํจํ๋ ๊ฐ์ฅ ๊ธด substring์ ๊ธธ์ด๋ฅผ ๊ตฌํด๋ผ.
Example 1 : Input : "eceba" Output : 3 Explanation : t is "ece" which its length is 3.
Example 2 : Input : "ccaabbb" Output : 5 Explanation : t is "aabbb" which its length is 5.
์๋ฃ๊ตฌ์กฐ : ์ ์ํ ๋ณ์ 4๊ฐ, Map(Character, Integer) 1. start : ์์ ์ธ๋ฑ์ค 2. end : ๋ ์ธ๋ฑ์ค 3. count : ๋ฌธ์์ด์ ๊ฐฏ์ 4. leng : ๋ฌธ์์ด์ ๊ธธ์ด(end-start ์ค ํฐ ๊ฐ)
์๊ณ ๋ฆฌ์ฆ 1. Map์ ์ ์ฅํ๋ค. - c 2๊ฐ, a 2๊ฐ, b 4๊ฐ => (c,2) (a,2) (b,4) 2. ๋ฌธ์์ ๊ฐฏ์๋ ์ต๋ 2๊ฐ์ด๋ค. - ๋ฌธ์ ๊ฐฏ์(count)๊ฐ 2๊ฐ ๋๋๋ค๋ฉด start(์์ ์ธ๋ฑ์ค)๋ก ์ด๋ฅผ ์ ์ดํ๋ค.
์๊ณ ๋ฆฌ์ฆ์ Java๋ก ๊ตฌํ
package java_basic;
import java.util.*;
public class LongestSubMostTwo {
public static void main(String[] args) {
String s = "ccaabbb";
System.out.println(solve(s));
}
private static int solve(String s) {
//1. ๊ทธ๋ฆ ์์ฑ
Map<Character, Integer> map = new HashMap<>();//(c,2) (a,2) (b,3)
int start = 0, end = 0, count = 0, leng = 0;
//2. ๋ฐ๋ณต๋ฌธ ๋๋ฆฐ๋ค.
while(end < s.length()) {
char c = s.charAt(end);
map.put(c, map.getOrDefault(c, 0)+1);//(c,2) (a,2)
if(map.get(c) == 1) count++;//new char, count๋ 2๊ฐ ๋๋ค.
end++;
while(count > 2) {//๋ฌธ์ ๊ฐฏ์๊ฐ 2๋ณด๋ค ๋ง์ผ๋ฉด!
char tmp = s.charAt(start);
map.put(tmp,map.get(tmp)-1);
if(map.get(tmp) == 0) {
count--;
}
start++;
}
//3. leng ๋ฆฌํด
leng = Math.max(leng, end-start);
}
return leng;
}
}
๋ฐฐ์ด ๋ด์ฉ ์ ๋ฆฌ(Java ๋ฌธ๋ฒ ๋ฐ ๋ฉ์๋) 1. Map.getOrDefault() : ์ฐพ๋ ํค๊ฐ ์กด์ฌํ๋ค๋ฉด ์ฐพ๋ ํค์ ๊ฐ์ ๋ฐํํ๊ณ ์๋ค๋ฉด ๊ธฐ๋ณธ ๊ฐ์ ๋ฐํํ๋ ๋ฉ์๋
getOrDefault(Object key, V DefaultValue)
char c = s.charAt(end);
map.put(c, map.getOrDefault(c, 0)+1);
//์ฒ์์๋ c๊ฐ map์ ์์ผ๋ 0์ ๋ฆฌํด.
//=>map.put(c,1)
//map์ (c,1)์ด ์กด์ฌํ๋๊น ํด๋น ๊ฐ์ธ 1์ ๋ฆฌํด!
//=>map.put(c,1+1)=>map.put(c,2)
Last updated
Was this helpful?