프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 한글자씩 읽어오도록 하기 - 어제 썼던 toCharArray()외에 string builder를 쓸 수 있을까? 생각해봄
2. n개만큼 반복시키기 - for외에 다른걸로 반복시킬 방법이 있을까?라고 생각해보면 while은 더 비효율적일것 같고.
3. 출력하기
1. 아는대로 풀기
class Solution {
public String solution(String my_string, int n) {
String answer ="";
for(char c : my_string.toCharArray()){
for(int i=0; i<n; i++)
answer+=c;
}
return answer;
}
}
어제 풀이의 연장선이라 크게 달라진게 없다.... 이중포문을 벗어나고 싶은데.
2. String builder를 쓸 수 있을까?
public class Programmers {
public static void main(String[] args) {
String my_string = "hello";
int n = 3;
String answer = "";
StringBuilder sb = new StringBuilder();
for (char c : my_string.toCharArray())
sb.append((c+"").repeat(n));
answer = sb.toString();
System.out.println(answer);
}
}
String java.lang.String.repeat(int count)
Returns a string whose value is the concatenation of this string repeated count times.
If this string is empty or count is zero then the empty string is returned.
- Parameters:count number of times to repeatReturns: A string composed of this string repeated count times or the empty string if this string is empty or count is zero
- Throws:IllegalArgumentException - if the count is negative.Since: 11
자료구조에서도 push()같이 넣는작업을 반복해서도 글자를 넣던데, 유사하게 쓸 수 있지 않을까? append를 돌려야하나? 라는 의문이 있었고, 싱글스레드인 경우에는 String 객체를 새로 만들고 연결하는 작업을 생략할 수 있는 String builder를 쓰는게 좋다.고 개념적으로만 알고있어서, 쓸수 있는지 생각을 했는데...
조리법을 모르겠어서 다른분 정답에서 힌트를 얻어 써보았다.
이때 repeat()메서드는 string builder에서 활용할 수 있는 메서드가 아니라, String이 문자열을 반복할 수 있도록 자바 11부터 추가된 메서드였음!
repeat관해서 찾다보니 왜 이렇게 해야하는지 알고리즘적으로 해설이 된 블로그를 보게 되었는데... 으으 갈길이 멀다
java string repeat 메서드로 쉽게 문자열을 반복해 봅시다.
카톡방에서 python은 'abc' * 5와 같은 문법이 있는데 자바에는 없는지 물어보셨습니다. java 8에서는 어떻게 쓰는지 잘 모르겠습니다. 아마, 이런 식으로 쓰지 않을까 싶습니다. "abc"를 10번 반복하기
codingdog.tistory.com
'🔥 Vamos > ALGORITHM' 카테고리의 다른 글
[프로그래머스/SQL] Lv2_DATETIME에서 DATE로 형 변환 (0) | 2024.05.02 |
---|---|
[프로그래머스/SQL] Lv2_카테고리별 상품 개수 구하기 (0) | 2024.05.02 |
[프로그래머스/Java] Lv0_모음제거 (2) | 2023.12.07 |
[프로그래머스/Java] Lv0_문자열 뒤집기 (String builder) (0) | 2023.08.27 |
[프로그래머스/Java] Lv0_특정 문자 제거 (0) | 2023.08.22 |