Algorithms/hash map

[Java] 암호 깨기 II (Crypt kicker II) - UVa 850문제

슬라임통통 2020. 10. 7. 14:44

[Java] 암호 깨기 II (Crypt kicker II) - UVa 850문제

 

onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=791

 

Online Judge

850 - Crypt Kicker II Time limit: 3.000 seconds

onlinejudge.org

문제 설명

 

내 코드

import java.io.*;
import java.util.*;

class Main {

	
	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		
		String standard = "the quick brown fox jumps over the lazy dog";

		
		
		int n = scanner.nextInt();
		scanner.nextLine();
		scanner.nextLine();	
		
		
		for(int i=0; i<n ; i++){
			TreeMap<Character,Character> rule = new TreeMap<Character,Character>();
			ArrayList<String> cryptlist = new ArrayList<String>();
			
			//입력하기
			while(scanner.hasNextLine()) {
				String input = scanner.nextLine();
				if(input.equals("")){
					break;
				}	
				cryptlist.add(input);	
			}
			
			
			//해당 암호 해쉬에 저장
			for(String str: cryptlist){
				if(str.length()==standard.length()){
					TreeMap<Character,Character> rule_copy = new TreeMap<Character,Character>();
					for(int j=0 ; j<str.length();j++){
						rule_copy.put(str.charAt(j), standard.charAt(j));
					}
					String result="";
					for(int j=0; j<str.length(); j++)
						result+=rule_copy.get(str.charAt(j));
						
						
					if(!result.equals(standard)) continue;
					else {
						
						rule.putAll(rule_copy); 
						break;
					}		 
					
				}
			}
		
			
			//출력하기
			String no_solution="";
			for(String str: cryptlist){
				String result="";
				for(int j=0; j<str.length(); j++){
					if(rule.get(str.charAt(j))==null){
						no_solution = "No solution.";
						break;
					}
					result+=rule.get(str.charAt(j));
				}
				if(no_solution.equals("No solution.")){
						break;
				}
				System.out.println(result);
			}
			if(no_solution.equals("No solution.")){
				System.out.println(no_solution);
			}
			System.out.println("");
			
		}
		
	}
}

 

🔑 Key Point 🔑

//해당 암호 해쉬에 저장
for(String str: cryptlist){
	if(str.length()==standard.length()){
		TreeMap<Character,Character> rule_copy = new TreeMap<Character,Character>();
		for(int j=0 ; j<str.length();j++){
			rule_copy.put(str.charAt(j), standard.charAt(j));
		}
		String result="";
		for(int j=0; j<str.length(); j++)
			result+=rule_copy.get(str.charAt(j));
						
		if(result.equals(standard)) {
			rule.putAll(rule_copy); 
			break;
		}			
	}
}

 

검사 str이 plain text랑 길이가 같으면 임시 TreeMap에 암호 대응을하여 다시 그 암호를 넣었을때 평서문이 나오면 기준 Map 완성 . 암호 Key value를 대응한 Map을 통하여 모든 input string 번역하여 출력!

 

굳이 좀더 빠르게 하려고 자꾸 if문을 남발할 필요가 없다 그러다가 알고리즘 짜는데 시간이 너무 오래걸림...

댓글수0