본문 바로가기

Programming/algorithm

[algorithm] 문자열 조합

문자열 조합


문제

문자열이 하나 주어졌을때, 문자열의 각 문자들을 조합하여 만들 수 있는 모든 경우를 출력하는 프로그램을 작성하라.

대문자 알파벳으로 이루어진 길이가 N인 문자열 (1≤N≤100)


입력 예제

ABC

가능한 모든 문자열 출력 (알파벳순으로 출력, 각 문자열은 공백으로 구분)


출력 예제

ABC ACB BAC BCA CAB CBA


문제 풀이

package algorithm;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

 

public class Main{

 

         private static String[] charData;

         private static char[] words;

 

         public static void main(String[] args) throws IOException {

                  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                  char[] arr = br.readLine().toCharArray();

                  words = new char[arr.length];

                  charData = new String[arr.length];

                  genWord(arr.length, 0, getRemainChar(arr, -1));

 }

 

         private static void genWord(int n, int depth, char[] remainWords){

                  for(int i = 0; i < n; i++){

                           words[depth] = remainWords[i];

                           if(remainWords.length == 1){

                                   for(int j = 0; j < charData.length; j++){

                                            System.out.print(words[j]);

                                   }

                                   System.out.println();

                           }

                           genWord(n - 1, depth + 1, getRemainChar(remainWords, i));

                  }

         }

 

         private static char[] getRemainChar(char[] source, int removeIdx){

                  if(removeIdx == -1){

                           return source;

                  }

 

                  char[] result = new char[source.length - 1];

                  int index = 0;

                  for(int i = 0; i < source.length; i++){

                           if(i != removeIdx){

                                   result[index] = source[i];

                                   index++;

                           }

                  }

                  return result;

         }

}




'Programming > algorithm' 카테고리의 다른 글

[algorithm] ABC  (0) 2016.04.02
[algorithm] 2007년  (0) 2016.04.02
[algorithm] 배열 요소 중 누락된 부분 찾기  (0) 2016.03.13
[algorithm] 팰린드롬 만들기  (0) 2016.03.11
[algorithm] 크로아티아 알파벳  (0) 2016.03.10