1. 내 코드
StringBuilder를 통해 값 변경 가능한 곳으로 옮겨주고 쌩구현했다.
나는 보통 쌩으로 구현하는 경우가 많은 것 같다. API를 좀 더 잘 이용하는 방법이 필요해보인다.
class Solution {
public String solution(String s) {
StringBuilder sb = new StringBuilder(s);
int wordIdx = 0;
for(int i = 0; i<s.length(); i++){
char ch = sb.charAt(i);
if(ch == ' ') {
wordIdx = 0;
continue;
}
if(wordIdx % 2 == 0 && ch >= 'a' && ch <= 'z') {
sb.setCharAt(i,(char) (ch - 32));
} else if(wordIdx % 2 == 1 && ch >= 'A' && ch <= 'Z') {
sb.setCharAt(i,(char) (ch + 32));
}
wordIdx++;
}
return sb.toString();
}
}
2. 다른 사람 코드
공백이 여러 개일 수도 있다는 말에 번거로울 것 같다고 생각해서 split 하지 않았는데, 오히려 하니까 좋은 것 같다.
그리고 공백에도 toLowerCase(), toUpperCase()가 사용이 가능하다는점 !
class Solution {
public String solution(String s) {
String answer = "";
int cnt = 0;
String[] array = s.split("");
for(String ss : array) {
cnt = ss.contains(" ") ? 0 : cnt + 1;
answer += cnt%2 == 0 ? ss.toLowerCase() : ss.toUpperCase();
}
return answer;
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 가장 가까운 같은 글자 (0) | 2025.02.26 |
---|---|
[프로그래머스] 시저 암호 (0) | 2025.02.26 |
[프로그래머스] 3진법 뒤집기 / 진법 변환 (0) | 2025.02.26 |
[프로그래머스] 같은 숫자는 싫어 (0) | 2025.02.25 |
[프로그래머스] 문자열 다루기 (0) | 2025.02.25 |