[Java] [Algorithm] Descending order of character strings

less than 1 minute read

Problem description

Create a method solution that takes the parameters of the string s, sorts them in descending order, and returns a new string.
s consists only of lowercase letters and uppercase letters, and uppercase letters are treated as values smaller than lowercase letters.

conditions

–Parameter: The length of s is a string of 1 or more.

Input / output example

| x | result |
|:—————–|——————:|
| “Zbcdefg”| “gfedcbZ”|

Commentary

  • The explanation is the code I wrote, so if you have a better algorithm, please share it!

Method 1


class Solution {
    public String solution(String s) {
        return Stream.of(s.split("")) //Split the string character by character
            .sorted(Comparator.reverseOrder()) //Sort in descending order
            .collect(Collectors.joining()); //Combine the divided character strings into one character string.
    }
}

Method 2


class Solution {
    public String solution(String s) {
        char[] sol = s.toCharArray(); //Get a char array from a string
        Arrays.sort(sol); // "Zbcdefg"

        //Use the StringBuilder reverse to reverse the order.
        return new StringBuilder(new String(sol)).reverse().toString();
    }
}
  • Personally, I like “Method 1” because it is simpler and easier to read.
    As for the speed, “Method 2” is faster.