Post

String_회문문자열_charAt, equalsIgnoreCase, stringBuilder, reverse

✅ 회문 문자열이니 ? YES : NO

회문 문자열: 앞에서 읽으나 뒤에서 읽으나 같은 문자열

  • string.charAt()사용해서 풀기
  • 어디까지만 비교하면 될까?
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.toLowerCase();
        int len= str.length();
        for(int i=0; i<len/2; i++){
            if(str.charAt(i) != str.charAt(len-i-1)) return "NO";
        }
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        String str= sc.next();
        System.out.println(T.solution(str));

    }

}


//⭐️input:
//gooG
//⭐️output:
//YES

🔵 ThingsILearned

✔️ 뒤에서부터 비교해올 때 str.charAt(len-i-1)로 뒤에서부터 가져올 수 있다.

이렇게 하면 똑같이 i를 사용하기 때문에 for문을 2개 사용할 필요가 없음!

🟢 String Builder, reverse, equalsIgnoreCase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Main {
    public String solution(String str){
        String answer= "YES";
        String tmp= new StringBuilder(str).reverse().toString(); //이렇게 한 줄에 쓰는 연습을 해 보자
        if(!str.equalsIgnoreCase(tmp)) return "NO";
        return answer;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        String str= sc.next();
        System.out.println(T.solution(str));

    }

}

🟢 for, if, equalsIgnoreCase

  • charArray만들어 풀기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Main {
    public String solution(String str){
        char[] charArr= str.toCharArray();
        String reverse= "";
        for(int i=charArr.length-1; i>=0; i--){
            reverse += charArr[i];
        }
        if(str.equalsIgnoreCase(reverse)){
            return "YES";
        } else{
            return "NO";
        }
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        String str= sc.next();
        System.out.println(T.solution(str));

    }

}
This post is licensed under CC BY 4.0 by the author.