알고리즘
백준 17609번 회문 C++
영춘권의달인
2021. 11. 15. 12:17
입력받은 문자열이 팰린드롬 이면 0, 문자 하나를 제거해서 팰린드롬이면 1, 둘 다 아니면 2를 출력하는 문제이다.
while문에서 문자열의 시작과 끝을 거리를 좁혀가면서 비교하면서 시작 지점이 끝 지점보다 커졌을 때까지 계속 같으면 팰린드롬이고, 만약 다르다면 시작 지점만 하나 늘리거나 끝 지점만 하나 줄여서 다시 비교를 한다.
여기서 하나 이상이 팰린드롬이라면 유사 팰린드롬이고, 둘 다 팰린드롬이 아니라면 그냥 일반 문자열이다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
bool isPalindrome(string str, int start, int end) {
while (start <= end) {
if (str[start] != str[end])
return false;
start++;
end--;
}
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
string str;
cin >> n;
while (n--) {
cin >> str;
int start = 0;
int end = str.length() - 1;
int ans = 2;
while (start <= end) {
if (str[start] != str[end]) {
if ((isPalindrome(str, start, end - 1) || isPalindrome(str, start + 1, end))) {
ans = 1;
}
break;
}
start++;
end--;
}
if (start > end) {
ans = 0;
}
cout << ans << "\n";
}
};