ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 9/26 TIL [프로그래머스 코딩테스트] 단 한문제
    프로그래밍/코딩테스트연습 2023. 9. 26. 15:52

    문자열 정렬하기(1)

    1. 반복문으로 문자를 제거하고 숫자만 담은 배열을 만든다

    2. sort로 정렬한 후 answer에 리턴 후 출력하면 될거라 생각했다.

    class Solution {
        public int[] solution(String my_string) {
            int[] answer = new int[my_string.length()];
           
            for(int i=0; i<my_string.length(); i++){
            char a = my_string.charAt(i);
                if('0'<=a && a<='9'){
                   answer[i]=a-'0'; 
                }else if(!('0'<=a && a<='9')){
                    continue;
                }
            }
            return answer;
        }
    }

    문자 또한 0으로 인식하는 문제가 있다.

    문자열일때는 값을 대입하지않거나 

    숫자가 나올때까지 같은 인덱스를 덮어 씌워야한다.

    다만 지금 answer[i]는 인덱스가 반복문을 통해 자동으로 증가하고 있기 때문에 i 대신 새로운 값을 넣어야했다.

    class Solution {
        public int[] solution(String my_string) {
            int[] answer = new int[my_string.length()];
            int b=0;
            for(int i=0; i<my_string.length(); i++){
            char a = my_string.charAt(i);
                if('0'<=a && a<='9'){
                   answer[b]=a-'0'; 
                    b++;
                }else if(!('0'<=a && a<='9')){
                    continue;        
                }
            }
            return answer;
        }
    }

    new int[my_string.length()]; 이 부분때문에 배열값이 문자일때 0으로 출력된다.

    import java.util.Arrays;
    class Solution {
        public int[] solution(String my_string) {
            int[] answer = new int[my_string.length()];
            int b=0;
            for(int i=0; i<my_string.length(); i++){
            char a = my_string.charAt(i);
                if('0'<=a && a<='9'){
                   answer[b]=a-'0'; 
                    b++;
                }else if(!('0'<=a && a<='9')){
                    continue;        
                }
            }
            int[] answer2=Arrays.copyOf(answer,b);
            Arrays.sort(answer2);
            return answer2;
        }
    }

    대충 이렇게 끝났다.

    더 좋은 방법이 무조건 있지만 짜증나서 다시 볼 생각은 안생김.

     

    다른 사람의 풀이

    import java.util.*;
    
    class Solution {
        public int[] solution(String my_string) {
    
            my_string = my_string.replaceAll("[a-z]","");
    
            int[] answer = new int[my_string.length()];
    
            for(int i =0; i<my_string.length(); i++){
                answer[i] = my_string.charAt(i) - '0';
            }
    
            Arrays.sort(answer);
    
            return answer;
        }
    }

    copyOf 까지는 어찌어찌 사용했는데 replaceAll은 생각도 못했다.

     

    하나 더 해야 하는데 하기 싫어서 여기까지

Designed by Tistory.