Develop
[프로그래머스] X 사이의 개수 본문
문제
내 풀이
class Solution {
public int[] solution(String myString) {
String[] answer = myString.split("x",-1);
int answer1[] = new int[answer.length];
for(int n = 0; n < answer.length; n++ ){
answer1[n] = answer[n].length();
}
return answer1;
}
}
느낀점
split을 써야하는 건 바로 알았지만
구분자가 맨 뒤에 있는 경우에는 마지막을 출력해주지 않았다
그럴 땐 split("구분자", -1) 을 해주면
구분자가 맨 뒤에 있어 마지막이 빈값이라도 반환처리 해준다
참고내용
[JAVA] split 빈값 처리 (tistory.com)
[JAVA] split 빈값 처리
문제상황 Java 서블릿 로직에서 split하는 로직이 있었는데 아래와 같은 상황에서 의도치 않은 동작이 발견되었습니다. String data = "1,2,3,,,"; String[] split_data = data.split(","); System.out.println("split length :
steady-snail.tistory.com
다른 풀이1
import java.util.Arrays;
class Solution {
public int[] solution(String myString) {
return Arrays.stream(myString.split("x", myString.length()))
.mapToInt(x -> x.length())
.toArray();
}
}
다른 풀이2
import java.util.*;
class Solution {
public Integer[] solution(String myString) {
return Arrays.stream(myString.split("x", -1)).map(String::length).toArray(Integer[]::new);
}
}
느낀점
음 내 코드가 제일 쉬운듯..
Map을 공부해놨더니 이젠 stream 이 나와서 stream을 공부해야겠다
'개인 공부 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] flag에 따라 다른 값 반환하기 (0) | 2024.01.17 |
---|---|
[프로그래머스] 조건 문자열 (0) | 2024.01.17 |
[프로그래머스] 한 번만 등장한 문자 (0) | 2024.01.16 |
[프로그래머스] 홀짝에 따라 다른 값 반환하기 (0) | 2024.01.15 |
[프로그래머스] 진료 순서 정하기 (1) | 2024.01.13 |