본문 바로가기

코딩테스트/프로그래머스

[프로그래머스][JAVA] A로 B 만들기 (LV.0)

반응형

 문제 설명

문자열 before와 after가 매개변수로 주어질 때, before의 순서를 바꾸어 after를 만들 수 있으면 1을, 만들 수 없으면 0을 return 하도록 solution 함수를 완성해보세요.

 

 제한사항

• 0 < before의 길이 == after의 길이 < 1,000
• before와 after는 모두 소문자로 이루어져 있습니다.

 

 입출력 예

before after result
"olleh" "hello" 1
"allpe" "apple" 0

 

※ 입출력 예 설명

입출력 예 #1

     • "olleh"의 순서를 바꾸면 "hello"를 만들 수 있습니다.

입출력 예 #2

     • "allpe"의 순서를 바꿔도 "apple"을 만들 수 없습니다.

 


나의 풀이
class Solution {
    public int solution(String before, String after) {
        int answer = 0;
        int bfLen = before.length();
        int afLen = after.length();
        String[] bfSt = new String[bfLen];
        String[] afSt = new String[afLen];
        
        String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        
        for(int i=0; i<bfLen; i++) {
            bfSt[i] = before.substring(i, i+1);
        }
        
        for(int i=0; i<afLen; i++) {
            afSt[i] = after.substring(i, i+1);
        }
        
        int lenBf = 0;
        int lenAf = 0;
        
        for(int i=0; i<bfLen; i++) {
            for(int j=0; j<alpha.length; j++) {
                if(bfSt[i].equals(alpha[j])) {
                    lenBf += j;
                }
            }
        }
        
        for(int i=0; i<afLen; i++) {
            for(int j=0; j<alpha.length; j++) {
                if(afSt[i].equals(alpha[j])) {
                    lenAf += j;
                }
            }
        }
        
        return lenBf == lenAf ? 1 : 0;
    }
}

 

다른 사람의 풀이
import java.util.Arrays;
class Solution {
    public int solution(String before, String after) {
        char[] a = before.toCharArray();
        char[] b = after.toCharArray();
        Arrays.sort(a);
        Arrays.sort(b);

        return new String(a).equals(new String(b)) ? 1 :0;
    }
}
728x90
반응형