blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Arrange a String in Descending Order (12917)

Complete a function, solution, that sorts the characters appearing in string s from largest to smallest and returns the new string. s consists only of uppercase and lowercase English letters, and uppercase letters are considered smaller than lowercase letters.

[Programmers / JAVA] Level 1 Arrange a String in Descending Order (12917)

Complete a function, solution, that sorts the characters appearing in string s from largest to smallest and returns the new string. s consists only of uppercase and lowercase English letters, and uppercase letters are considered smaller than lowercase letters.
RWB0104
@RWBwritten at 2021-12-16 12:31:37
Programmers

시리즈 모아보기

Programmers

42 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Arrange a String in Descending Order

Complete a function, solution, that sorts the characters appearing in string s from largest to smallest and returns the new string.

s consists only of uppercase and lowercase English letters, and uppercase letters are considered smaller than lowercase letters.

  • str is a string of length 1 or more.
sreturn
"Zbcdefg""gfedcbZ"

A function that sorts the characters of s in descending order. Without needing to worry about anything else, this can be solved simply by comparing the ASCII code value of each character.

  • A to Z: 65 ~ 90
  • a to z: 97 ~ 122

Since the code value of uppercase letters is smaller than that of lowercase letters, this exactly matches the problem's condition.

When sorting, take the ASCII code value of each character in the string and sort by that.

JAVA

import java.util.List;
import java.util.stream.Collectors;

/**
 * Arrange a String in Descending Order class
 *
 * @author RWB
 * @since 2021.12.13 Mon 15:11:19
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param s: [String] string
	 *
	 * @return [String] the answer
	 */
	public String solution(String s)
	{
		List<String> list = s.chars().sorted().mapToObj(Character::toString).collect(Collectors.toList());;
		
		StringBuilder builder = new StringBuilder();
		
		for (int i = list.size() - 1; i > -1; i--)
		{
			builder.append(list.get(i));
		}
		
		return builder.toString();
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08