KOI2019 초등부 2번 문제(G5) 입니다.
투포인터로 접근했습니다. 문자열의 앞과 뒤에서 하나씩 오면서 문자가 같은지 확인하다가 일치하지 않는 문자가 나오면 해당 인덱스를 저장합니다. 기존 문자열을 두 개로 복제해서 앞서 저장했던 인덱스를 각각 앞, 뒤에서 제거해주고 다시 탐색하면서 일치하지 않는 문자가 또 발생하면 “2”를 출력, 그렇지 않으면 “1”을 출력합니다.
#include <iostream>
#include <string>
#include <string.h>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int T; cin >> T;
while(T--){
string str, _str; cin >> str;
_str = str;
int flag = 0;
int i = 0, j = str.length() - 1;
while(i <= j){
if(str[i] != str[j]){
flag = 2;
break;
}
i++; j--;
}
if(flag == 0){
cout << 0 << "\n";
}
else{
flag = 0;
int f1 = 0, f2 = 0;
str.erase(i, 1);
_str.erase(j, 1);
i = 0; j = str.length() - 1;
while(i <= j){
if(str[i] != str[j]){
f1 = 1;
}
if(_str[i] != _str[j]){
f2 = 1;
}
i++; j--;
}
if(f1 + f2 == 2){
flag = 1;
}
if(flag == 1){
cout << 2 << "\n";
}
else{
cout << 1 << "\n";
}
}
}
}