01. 문제
https://school.programmers.co.kr/learn/courses/30/lessons/12930
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문자열 s는 한 개 이상의 단어로 구성되어 있다. 각 단어는 하나 이상의 공백문자로 구분되어 있고, 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하는 문제이다.
02. 문제 풀이로 배운점
이번 문제는 String을 사용하여 풀이하였지만 runtime이 생각보다 오래 걸려서 저번에 사용해봤던 StringBuilder를 사용해보았다.
아래 사진에서 확인할 수 있듯이 최대 5.79ms 가나오던 테스트8번이 0.15ms 으로 개선된 모습을 볼 수 있다.
🙊StringBuilder는 왜 빠를까?
String은 immutable('불변의')객체이다. 불변이라니.... 분명 내가 사용한 Java의 String은 길이를 늘리거나 줄일 수 있었는데! Java에서는 String은 변한 것 처럼 보여진다. 즉 String 객체는 변하지 않는다. 아래와 같이 String문자열을 더하게 되면 새로운 String 객체가 생성되고, 기존 객체는 버려진다. 계속해서 더하면 계속해서 새로생기고 버리는 작업을 반복한다는 것이다! 🥲
String text = "오";
text = text + "잉";
/*
결과 : "오잉"
"오"를 가지고 있는 객체는 더 이상 사용할 수 없다. 즉 GC의 대상이 된다.
*/
🙊StringBuilder와 Buffer의 공통점과 차이점
불변한 String 클래스의 단점을 보완하기 위해서 나온 클래스가 StringBuilder와 StringBuffer이다.
StringBuilder와 StringBuffer의 공통점은 모두 문자열을 다룬다는 것이고, CharSequence 인터페이스를 구현했다는 점이다. 따라서 매개변수로 받는 작업을 할 때 CharSequence타입으로 받는 것이 좋다.
StringBuilder와 StringBuffer의 차이점은 StringBuilder는 쓰레드 동기화를 제외하고 있다. 따라서 단일 Thread인 경우와 빠른 속도, 가변적인 문자열을 사용할 때는 StringBuilder를 사용하는 것이 적합하다.
JDK5 이상에서는 String 더하기 연산의 경우, 컴파일 할 때 자동으로 해당 연산을 StinrgBuilder로 변환해준다고 한다. 하지만 for와 같은 반복연사느이 경우 자동 변환을 지원하지 않으므로 꼭 필요하다!
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
StringBuilder (Java Platform SE 8 )
Inserts the string into this character sequence. The characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by
docs.oracle.com
🙊StringBuilder와 Buffer의 유의사항
StringBuffer는 인스턴스를 생성할 때 그 크기를 지정할 수 있다. 이 때 편집할 문자열의 길이를 고려하여 버퍼의 길이를 충분히 잡아주는 것이 좋다. 편집 중인 문자열이 버퍼의 길이를 넘어서게 되면 버퍼의 길이를 늘려주는 작업이 추가로 수행되어야하기 때문에 작업 효율이 떨어진다.
03. 문제 풀이 코드
- String 을 사용한 풀이
class Solution {
public String solution(String s) {
String answer = "";
int index = 0;
for(int i = 0; i < s.length(); i++){
String temp = String.valueOf(s.charAt(i));
if(temp.equals(" ")){
answer = answer + " ";
index = 0;
} else if (index % 2 == 0){
answer = answer + temp.toUpperCase();
System.out.println(answer);
index += 1;
} else if(index % 2 == 1){
answer = answer + temp.toLowerCase();
System.out.println(answer);
index += 1;
}
}
return answer;
}
}
// TRYhELLOwORLD
// TrY HeLlO WoRlD
- StringBuilder를 사용한 풀이
class Solution {
public StringBuilder solution(String s) {
StringBuilder answer = new StringBuilder();
int index = 0;
for(int i = 0; i < s.length(); i++){
String temp = String.valueOf(s.charAt(i));
if(temp.equals(" ")){
answer = answer.append(" ");
index = 0;
} else if (index % 2 == 0){
answer = answer.append(temp.toUpperCase());
index += 1;
} else if(index % 2 == 1){
answer = answer.append(temp.toLowerCase());
index += 1;
}
}
return answer;
}
}
'Algorithm' 카테고리의 다른 글
[Algorithm] Maximum Depth of Binary Tree (0) | 2023.06.15 |
---|---|
[Algorithm]3진법 뒤집기(2.87ms -> 0.05ms) (0) | 2023.06.11 |
[Algorithm]Two Sum (63ms -> 2ms 개선) (0) | 2023.06.10 |
[Algorithm]삼각달팽이(Java) (0) | 2023.05.24 |
[Algorithm]교점에 별만들기(Java) (0) | 2023.05.23 |
댓글