問題説明
文字列sのパラメータを受け取り、降順でソートを行って新しい文字列を返却するメソッドsolutionを作成してください。
sは英文字の小文字、大文字のみで構成されていて、大文字は小文字より値が小さい値として扱う。
条件
- パラメータ:sの長さは1以上の文字列です。
入出力の例
x | result |
---|---|
"Zbcdefg" | "gfedcbZ" |
解説
※解説は私が作成したコードなので、もっといいアルゴリズム等々ありましたら、共有してください!
方法1
class Solution {
public String solution(String s) {
return Stream.of(s.split("")) // 文字列を1文字ずつ分割
.sorted(Comparator.reverseOrder()) // 降順にソート
.collect(Collectors.joining()); // 分割した文字列を1つの文字列にする。
}
}
方法2
class Solution {
public String solution(String s) {
char[] sol = s.toCharArray(); // 文字列からchar配列を取得
Arrays.sort(sol); // "Zbcdefg"
// StringBuilderのreverseを利用して逆順にする。
return new StringBuilder(new String(sol)).reverse().toString();
}
}
※個人的には「方法1」のほうが簡略で読みやすくて好きですが、
速度のほうは「方法2」のほうが早いですね。