백준 17609

hyoJeong·2021년 9월 20일
0

문제 링크: https://www.acmicpc.net/problem/17609
알고리즘: 구현,문자열,두 포인터
문제 해결 idea: 앞 뒤 방향으로 볼때 같은 순서의 문자로 구성된 문자열을 회문 또는 펠린드롬이라 한다.
문자의 앞과 뒤가 동일해야 하기 때문에 투포인터를 이용해 문제해결 방향을 잡았다.
문자열의 인덱스를 나타내는 lt,rt변수를 선언하고, 이 변수를 사용해 회문의 여부를 확인한다.
중요한 점은 유사회문의 여부를 판단하는 것인데, 앞쪽 문자를 생략할 경우와 뒤의 문자를 생략할 경우에 따라 회문가능 여부가 변경될 수 있다. 따라서 앞쪽문자를 생략해 회문, 유사회문 여부를 판단하고 회문이 아닐경우, 뒤의 문자를 생략하는 경우로 다시 한번 문자열을 비교한뒤, 회문, 유사회문, 회문이 아닐경우를 판단한다.
처음 문제를 풀었을때, 틀린 반례: cccfccfcc일때 결과는 1이 나와야 한다.

문제 코드 :

#include <iostream>
#include <algorithm>
#include <vector>


using namespace std;

int main(){
    cin.tie(0);
    cout.tie(0);
    std::ios::sync_with_stdio(false);
    int n;
    cin>>n;
    
    while(n--){
        string s;
        cin>>s;
        int lt=0;
        int rt=(int)s.size()-1;
        int cnt=0;
        bool ch1=true;
        bool ch2=false;
        while(lt<=rt){
            if(s[lt]==s[rt]){
                lt++;
                rt--;
            }else{

                //유사 회문인경우
                if(cnt<1&&s[lt]==s[rt-1]){
                    cnt++;
                    ch2=true;
                    lt++;
                    rt-=2;
                }else if(cnt<1&&s[lt+1]==s[rt]){
                    cnt++;
                    lt+=2;
                    rt--;
                    ch2=true;
                }else{
                    ch1=false;
                    break;
                }
            }
        }
        if(ch1==true&&ch2==false){
            cout<<0<<"\n";
        }else if(ch1==true&&ch2==true){
            cout<<1<<"\n";
        }else if(ch1==false){
            ch1=true;
            ch2=false;
            lt=0;
            cnt=0;
            rt=(int)s.size()-1;
            while(lt<=rt){
                if(s[lt]==s[rt]){
                    lt++;
                    rt--;
                }else{
                   if(cnt<1&&s[lt+1]==s[rt]){
                        cnt++;
                        lt+=2;
                        rt--;
                        ch2=true;
                    }else{
                        ch1=false;
                        break;
                    }
                }
            }
            if(ch1==true&&ch2==false){
                cout<<0<<"\n";
            }else if(ch1==true&&ch2==true){
                cout<<1<<"\n";
            }else{
                cout<<2<<"\n";
            }

        }



    }






    return 0;
}

0개의 댓글