https://www.acmicpc.net/problem/20437
20437번: 문자열 게임 2
첫 번째 문자열에서 3번에서 구한 문자열은 aqua, 4번에서 구한 문자열은 raquator이다. 두 번째 문자열에서는 어떤 문자가 5개 포함된 문자열을 찾을 수 없으므로 -1을 출력한다.
www.acmicpc.net
과정
- 입력받은 문자열의 idx를 하나 씩 벡터에 저장합니다.
- 만약 해당 알파벳의 갯수가 K보다 작으면 넘깁니다.
- 알파벳의 모든 idx를 돌며 최소와 최대값을 구합니다.
코드
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int T, K;
string str;
void calc(){
vector<vector<int> > arr(27);
int ans1 = 987'654'321, ans2 = 0;
for(int i=0;i<str.length();++i){
int num = str[i]-'a';
arr[num].push_back(i);
}
for(int i=0;i<27;++i){
if(arr[i].size() < K)
continue;
int l = 0, r = K-1;
while(r < arr[i].size()){
ans1 = min(ans1, arr[i][r] - arr[i][l] + 1);
ans2 = max(ans2, arr[i][r] - arr[i][l] + 1);
++l;
++r;
}
}
if(ans1 == 987'654'321)
cout<<-1<<'\n';
else
cout<<ans1<<" "<<ans2<<'\n';
}
void input(){
cin>>T;
while(T--){
cin>>str>>K;
calc();
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
input();
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| 1943 - 동전 분배 (0) | 2023.07.25 |
|---|---|
| 14719 - 빗물 (0) | 2023.07.25 |
| 17615 - 볼 모으기 (0) | 2023.07.23 |
| 24337 - 가희와 탑 (0) | 2023.07.22 |
| 2531 - 회전 초밥 (0) | 2023.07.22 |
댓글