카테고리 없음

[JAVA] 특수문자가 섞인 팔린드롬(replaceAll)

puzzling 2021. 4. 13. 22:21
  • 문제
앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라고 합니다.

문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력하는 프로그램을 작성하세요.

단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않습니다.

알파벳 이외의 문자들은 무시
  • 키포인트
알파벳 이외의 문자를 replaceAll로 공백처리해주는것
공백처리시에 정규식 사용, replace에서는 사용 불가 only replaceAll

그리고 다시 StringBuilder사용한 회문문자열 비교
  • 풀이
package chapter1;

import java.util.Scanner;

public class 문자팔린드롬 {

  public static String solution(String str) {
      String answer = "NO";
      str = str.toLowerCase().replaceAll("[^a-z]", "");
      String tmp = new StringBuilder(str).reverse().toString();
      if(tmp.equals(str))answer ="YES";

      return answer;
  }

  public static void main(String[] args){
    Scanner in=new Scanner(System.in);

    String str = in.nextLine();
    System.out.println(solution(str));

    in.close();

  }
}