String_팰린드롬_replaceAll
✅ 팰린드롬이면 YES, 아니면 NO, 알파벳 대소문자 무시, 알파벳 이외의 문자들 무시
💡 팰린드롬: 앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Main {
public String solution(String str){
String answer= "YES";
str= str.replaceAll("[^a-zA-Z]+","").toLowerCase();
int len= str.length();
for(int i=0; i<len/2; i++){
if(str.charAt(i) != str.charAt(len-1-i)) return "NO";
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
String str= sc.nextLine();
System.out.println(T.solution(str));
}
}
//⭐️input:
//found7, time: study; Yduts; emit, 7Dnuof
//⭐️output:
//YES
🔵 ThingsILearned
✔️ replaceAll()
two parametwes, (rule, toReplaceWith) replaceAll("[^a-zA-Z]+","")
하면 알파벳 아닌 기호, 띄어쓰기, 숫자 등은 다 ""
, 즉 사라진다. ^
아니다(부정), a-z
소문자 그리고 A-Z
대문자 따라서 소문자나 대문자 아니면, ""
아무것도 없게 replace
또는 먼저 소문자로 만들고, 소문자만 아니면으로 코드도 가능 str= str.toLowerCase().replaceAll("[^a-z]+","");
🟢 StringBuilder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Main {
public String solution(String str){
String answer= "YES";
str= str.replaceAll("[^a-zA-Z]+","").toLowerCase();
String tmp= new StringBuilder(str).reverse().toString();
if(!str.equals(tmp)) return "NO";
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
String str= sc.nextLine();
System.out.println(T.solution(str));
}
}
This post is licensed under CC BY 4.0 by the author.