[JAVA] [Algorithm] Descending order of character strings

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

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();
    }
}

Recommended Posts

[Algorithm] Descending order of character strings
[Java] Comparison of String type character strings
[Algorithm] Addition of digits
About full-width ⇔ half-width conversion of character strings in Java
[Java] Handling of character strings (String class and StringBuilder class)
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
Basics of character operation (java)
[Ruby] Repeating arbitrary character strings
Display character strings character by character [Note]