๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ƒํ•œ ๋ฌธ์ž ๋งŒ๋“ค๊ธฐ

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ƒํ•œ ๋ฌธ์ž ๋งŒ๋“ค๊ธฐ

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

๋ฌธ์ œ์ ‘๊ทผ

๋ฌธ์ž์—ด์„ ๊ณต๋ฐฑ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๋‚˜๋ˆ ์ง„ ๋‹จ์–ด๋“ค์„ ๊ธฐ์ค€์œผ๋กœ ์ง์ˆ˜๋Š” ๋Œ€๋ฌธ์ž๋กœ, ํ™€์ˆ˜๋Š” ์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊พธ๋Š” ๋ฌธ์ œ์ด๋‹ค.
splitํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ๋‹จ์–ด๋ฅผ ๋‚˜๋ˆ„๊ณ , ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ง์ˆ˜, ํ™€์ˆ˜๋ฅผ ๊ตฌ๋ถ„ํ•ด์„œ ๋Œ€๋ฌธ์ž,์†Œ๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์ฃผ์—ˆ๋‹ค.

Code

class Solution {
    public String solution(String s) {
        String[] words = s.split(" ");
        StringBuilder answer = new StringBuilder();
        for(int i = 0; i<words.length; i++){
            char[] word = words[i].toCharArray();
            for(int j = 0; j<word.length; j++){
                if(j%2==0){
                    word[j] = Character.toUpperCase(word[j]);
                } else {
                    word[j] = Character.toLowerCase(word[j]);
                }
            }
            answer.append(word);
            if(i != words.length-1)
                answer.append(" ");
        }
        if(s.length() > answer.length())  // ์ž…๋ ฅ ๋ฌธ์ž์—ด ๋’ค์— ๊ณต๋ฐฑ์ด ๋” ์žˆ์„ ๊ฒฝ์šฐ
            answer.append(s.substring(answer.length()));

        return answer.toString();
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

์ฒ˜์Œ์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ๋งž์•˜๋Š”๋ฐ ์ œ์ถœํ•ด๋ณด๋‹ˆ๊นŒ ํ‹€๋ ธ๋‹ค๊ณ  ํ•ด์„œ ๋‹นํ™ฉ์„ ํ–ˆ์—ˆ๋‹ค.
์ด์œ ๋ฅผ ์•Œ๊ณ ๋ณด๋‹ˆ "try hello world "๋ฅผ ์ž…๋ ฅ์„ ๋ฐ›์œผ๋ฉด "TrY HeLlO WoRlD "๋ฅผ ์ถœ๋ ฅํ•ด์•ผํ•˜๋Š”๋ฐ, "TrY HeLlO WoRlD" ๋’ค์— ๊ณต๋ฐฑ์„ ์ถœ๋ ฅํ•˜์ง€ ์•Š๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค. ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ์œ„ํ•ด์„œ ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜์˜€๋‹ค.

 if(s.length() > answer.length())  // ์ž…๋ ฅ ๋ฌธ์ž์—ด ๋’ค์— ๊ณต๋ฐฑ์ด ๋” ์žˆ์„ ๊ฒฝ์šฐ
            answer.append(s.substring(answer.length()));

๊ทธ๋ฆฌ๊ณ  ๊ตณ์ด String์—์„œ ํ•œ ๊ธ€์ž์”ฉ ์ ‘๊ทผํ•  ๋•Œ CharArray๋กœ ์ ‘๊ทผํ•˜์ง€ ์•Š๊ณ  String์œผ๋กœ ์ ‘๊ทผํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™๋‹ค.(๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ๊นŒ ๋ชจ๋‘ String์œผ๋กœ ๊ทธ๋ƒฅ index๋กœ ์ ‘๊ทผ์„ ํ•œ๋‹ค.)

๋ฐ˜์‘ํ˜•