algorithm

특정 문자 뒤집기

juuuuuuun 2024. 4. 9. 14:27
5. 특정 문자 뒤집기
 

설명

영어 알파벳과 특수문자로 구성된 문자열이 주어지면 영어 알파벳만 뒤집고,

특수문자는 자기 자리에 그대로 있는 문자열을 만들어 출력하는 프로그램을 작성하세요.

 

입력

첫 줄에 길이가 100을 넘지 않는 문자열이 주어집니다.

 

출력

첫 줄에 알파벳만 뒤집힌 문자열을 출력합니다.

 

예시 입력 1 

a#b!GE*T@S

 

예시 출력 1

S#T!EG*b@a

 

소스코드 1

import java.util.Scanner;

public class Main {
    public static String solution(String str) {
        String answer;
        int lt = 0;
        int rt = str.length() - 1;
        char[] s = str.toCharArray();
        while (lt < rt) {
            if (('A' > s[lt] || s[lt] > 'z')) { //왼쪽이 특수문자이면
                lt++;
            } else if (('A' > s[rt] || s[rt] > 'z')) { //오른쪽이 특수문자이면
                rt--;
            } else { //모두 특수문자가 아니면
                char tmp = s[lt];
                s[lt] = s[rt];
                s[rt] = tmp;
                lt++;
                rt--;
            }
        }
        answer = String.valueOf(s);
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        System.out.println(solution(str));

    }
}

 

 

소스코드 2

import java.util.Scanner;

public class Main {
    public static String solution(String str) {
        String answer;
        int lt = 0;
        int rt = str.length() - 1;
        char[] s = str.toCharArray();
        while (lt < rt) {
            if (!Character.isAlphabetic(s[lt])) { //왼쪽이 특수문자이면
                lt++;
            } else if (!Character.isAlphabetic(s[rt])) { //오른쪽이 특수문자이면
                rt--;
            } else { //모두 특수문자가 아니면
                char tmp = s[lt];
                s[lt] = s[rt];
                s[rt] = tmp;
                lt++;
                rt--;
            }
        }
        answer = String.valueOf(s);
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        System.out.println(solution(str));

    }
}

 

 

Character.isAlphabetic()

 - 파라미터가 알파벳인지 아닌지 검증해 준다

'algorithm' 카테고리의 다른 글

회문 문자열  (0) 2024.04.09
중복 문자 제거  (0) 2024.04.09
단어 뒤집기 / ArrayList, StringBuilder  (1) 2024.04.09
문장 속 단어  (0) 2024.04.08
대소문자 변환  (0) 2024.04.08