[String] 17609번 - 회문(47일차)

bob.sort·2021년 7월 25일
0

1일 1백준 운동 - C/C++

목록 보기
14/14
post-thumbnail
//기본 모듈 import
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;


//유사 회문 판단 함수 (TF 반환하므로 bool 함수로 선언)
bool pseudo(string a, int left, int right){
  //회문 탐색이 종료될 때까지
  while (left < right){
    //왼쪽 글자와 오른쪽 글자가 같다면
    if (a[left] == a[right]){
      //탐색위치를 좌우로 한칸씩 이동
      left++;
      right--;
    //글자가 다르다면
    }else{
      //유사 회문이 아님을 반환
      return false;
    }
  }
  //모든 탐색 후 회문이면 true를 반환
  return true;
}

//회문 판단 함수
int palindrome(string a, int left, int right){
  //회문 탐색이 종료될 때까지
  while(left < right){
    //좌우 글자가 같다면
    if(a[left] == a[right]){
      //좌우로 한칸씩 이동해서 재탐색
      left++;
      right--;
    //좌우 글자가 다르다면
    }else{
      //왼쪽 글자를 이동했을 때 회문인지를 판단
      bool res1 = pseudo(a, left+1, right);
      //오른쪽 글자를 이동했을 때 회문인지를 판단
      bool res2 = pseudo(a, left, right-1);
      //두 경우 중 회문이 하나라도 있으면
      if(res1 == true || res2 == true){
        //1(유사회문)을 반환
        return 1;
      //회문이 하나도 없으면
      }else{
        //2(회문 아님)을 반환
        return 2;
      }
    }
  }
  //모든 탐색시 회문이면 0 반환
  return 0;
}

int main(){
  //반복 횟수 입력
  int n;
  cin >> n;

  while(n--){
    //문자열을 입력받고
    string line;
    cin >> line;
    //해당 문자열을 기준으로 좌측 끝과 우측 끝에서 회문 탐색
    int res = palindrome(line, 0, sizeof(line)-1);
    //결과값 출력
    cout << res;
  }
}
profile
Interest in Computer Graphics and Computer Vision

0개의 댓글