티스토리 뷰

https://programmers.co.kr/learn/courses/30/lessons/12930

 

코딩테스트 연습 - 이상한 문자 만들기

문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을

programmers.co.kr

 

[문제 풀이]

 

1. 각 단어별 index를 알고 있어야 한다.

  1-1. 처음 index는 0이다.

  1-2. 빈칸이 아닐 경우 index는 1씩 증가

  1-3. 빈칸일 경우 index는 다시 0

2. index가 짝수이면 대문자로 변경한다.

3. index가 홀수이면 소문자로 변경한다.

 

[소스 코드]

 

public class MakingWeirdWords {

    private static StringBuilder stringBuilder = new StringBuilder();

    public static void main(String[] args) {
        String s = " abc ";

        System.out.println(solution(s));
    }

    private static String solution(String s) {
        int index = 0;
        char[] texts = s.toCharArray();

        for (char text : texts) {
            if (text == ' ') {
                index = 0;
                stringBuilder.append(" ");
                continue;
            }
            convertWord(index, text);
            index++;
        }

        return stringBuilder.toString();
    }

    private static void convertWord(int index, char text) {
        if (index % 2 == 0) {
            stringBuilder.append(String.valueOf(text).toUpperCase());
            return;
        }
        stringBuilder.append(String.valueOf(text).toLowerCase());
    }
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
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 26 27 28
글 보관함