https://www.acmicpc.net/problem/16472
16472번: 고냥이
고양이는 너무 귀엽다. 사람들은 고양이를 너무 귀여워했고, 결국 고양이와 더욱 가까워지고 싶어 고양이와의 소통을 위한 고양이 말 번역기를 발명하기로 했다. 이 번역기는 사람의 언어를 고
www.acmicpc.net
저는 투포인트를 이용해 문제를 해결하였습니다.
시작포인트와 끝 포인트 사이에 몇개의 알파벳 종류가 있는지를 체크하였습니다.
종류가 n개 초과한다면 시작 포인트를 늘리고 이하라면 끝 포인트를 늘려 시작 포인트와 끝 포인트의 최대 값을 찾고 리턴하였습니다.
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
public class BOJ_16472 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(br.readLine());
String command = br.readLine();
int result = cal(command,n);
System.out.println(result);
}
private static final int ALPHABET_SIZE = 26;
private static int cal(String command, int n) {
int result = 0;
int si = 0;
int ei = 0;
int cnt = 0;
int[] used = new int[ALPHABET_SIZE];
while(true){
result = Math.max(result,ei-si);
if(ei >= command.length()){
break;
}
int now = command.charAt(ei) - 'a';
if(used[now] > 0 || cnt < n){
if(used[now] == 0){
cnt++;
}
used[now]++;
ei++;
continue;
}
if(cnt >= n){
int prev = command.charAt(si) - 'a';
used[prev]--;
if(used[prev] == 0){
cnt--;
}
si++;
continue;
}
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 4158번 CD (JAVA) (0) | 2022.08.26 |
---|---|
백준 1833번 고속철도 설계하기 (JAVA) (1) | 2022.08.25 |
백준 1826번 연료 채우기 (JAVA) (0) | 2022.08.23 |
백준 14562번 태권왕 (JAVA) (0) | 2022.08.22 |
백준 1337번 올바른 배열 (JAVA) (0) | 2022.08.21 |