기타 사이트/이코테

[구현문제] 문자열 재정렬

빙수빈수 2021. 6. 15. 15:19

[문제]

 알파벳 대문자와 숫자(0~9)로만 구성된 문자열이 입력으로 주어질때, 모든 알파벳을 오름차순으로 정렬하여 출력한 뒤에 모든 숫자를 더한 값을 출력하는 프로그램을 작성하시오.

 

[코드]

import java.util.*;

public class realization_p322 {
	public static String str;
	public static int sum=0;
	public static ArrayList<Character> result=new ArrayList<Character>();
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		str=sc.nextLine();
		
		// 입력받은 문자열을 문자 하나씩 확인하며 문자인 경우에는 연결리스트에 저장, 숫자인 경우 합산
		for(int i=0;i<str.length();i++) {
			if(Character.isLetter(str.charAt(i)))
				result.add(str.charAt(i));
			else 
				sum+=str.charAt(i)-'0';
		}
		
		// 알파벳을 오름차순으로 정렬
		Collections.sort(result);
		
		for (int i = 0; i < result.size(); i++) {
            System.out.print(result.get(i));
        }
		
		// 숫자가 하나라도 존재하는 경우 가장 뒤에 출력
        if (sum != 0) System.out.print(sum);
        System.out.println();
	}
}

 

[고찰]

 Character.isLetter() 함수를 사용하면 해당 문자가 알파벳인지 판단해주는 함수를 알지 못해 풀이를 참고한 문제였다. 또한 배열을 사용하여 문자에 접근하는 것 보다는 연결리스트를 사용하여 문자를 다루는 것이 더 편리하는 것을 알았다.