import java.util.Arrays;
public class ReverseStr {
public String reverseStr(String str){
char[] sol = str.toCharArray();
Arrays.sort(sol);
return new StringBuilder(new String(sol)).reverse().toString();
}
}
속도는 느리지만 stream을 사용하면 아래 처럼 풀 수 있다.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.Comparator;
public class ReverseStr {
public String reverseStr(String str){
return Stream.of(str.split(""))
.sorted(Comparator.reverseOrder())
.collect(Collectors.joining());
}
}
비교 분석
StringBuilder를 활용하면 역순 정렬을 쉽게 할 수 있다.
StringBuilder에 대한 학습이 필요함.
비교 분석 반영
import java.util.*;
class Solution {
public String solution(String s) {
if(s.length() == 1){
return s;
}
char[] arr = s.toCharArray();
Arrays.sort(arr);
return new StringBuilder(new String(arr)).reverse().toString();
}
}