자바로 백준 1342 풀기

hong030·2023년 7월 22일
0
  • 실버 1단계 문제

풀이)
DFS를 이용하여 문자열이 주어졌을 때 두 가지 비교를 통해 행운의 문자열을 찾아낸다.

  1. 사용할 알파벳이 있느냐
  2. 이전 알파벳이 현재 알파벳과 같느냐

내 코드)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

public class Main {

	static char[] alphabet = new char[27];
	static boolean[] visited;
	static int result = 0;
	
	public static void DFS(int idx, String temp, int len) {
		
		if(idx == len) {
			result++;
			return;
		}
		
		for(int i = 0; i < 26; i++) {
			if(alphabet[i] == 0)
				continue;
			if(temp != "" && temp.charAt(temp.length() - 1) == (char)('a' + i))
				continue;
			alphabet[i]--;
			DFS(idx + 1, temp + (char)('a' + i), len);
			alphabet[i]++;
		}
	}
	
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		
		
		for(int  i = 0; i < str.length(); i++)
			alphabet[str.charAt(i) - 'a']++;

		DFS(0, "", str.length());
		
		System.out.println(result);
		
	}
	
}
profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

1개의 댓글

comment-user-thumbnail
2023년 7월 22일

잘 봤습니다. 좋은 글 감사합니다.

답글 달기