글자 단어 개수 세기 [Java]

문제 설명

 

내 코드

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



class Main{

	public static void main(String [] args){
    
    	Scanner scanner = new Scanner(System.in);
        
        while(scanner.hasNextLine()){    
        	String str = scanner.nextLine();
        	int words=0, letters=0;


         	String []word = str.split(" \t");
         	words = word.length;
          
          
         	for(int i=0; i<str.length; i++){
          		if( str.charAt(i) != " " && str.charAt(i) != "\t")
                	letters+=1;
          	}

          System.out.println(words + " " + letters);
        }
        
    }
}

 

🔑 Key Point 🔑

String객체에 쓰는 split 함수 

String [] s = str.split(" ");  str을 공백의 단위로 쪼개어 s 배열에 단어를 자동 넣어준다 !

UVa Online Judge - 10252번 Common Permutation

[Java]  공통된 변경 문자열(Common Permutation)

 

문제 설명

 

 

 

내 코드

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

class Main {
	
	public static void main(String[] args) throws Exception {
		
		Scanner scanner = new Scanner(System.in);
		
		while(scanner.hasNextLine()){
	
			String input1 =scanner.nextLine();
			String input2 =scanner.nextLine();
			
			Vector<Character> str1 = new Vector<Character>();
			Vector<Character> str2 = new Vector<Character>();
			ArrayList<Character> result= new ArrayList<Character>();
			
			//입력 스트링 벡터에 저장
			for(int j=0; j<input1.length();j++)
				str1.add(input1.charAt(j));
			
			for(int j=0; j<input2.length();j++)
				str2.add(input2.charAt(j));
			

			//하나하나 대조하여 발견되면 벡터에서 제거해준다.
			for(int j=0; j<str1.size(); j++){
				for(int k=0; k<str2.size();k++){
					if(str1.get(j)==str2.get(k)){
						result.add(str1.get(j));
						str2.remove(k);
						break;
					}
				}
			}
			
			//오름차순 정렬
			Collections.sort(result, new Comparator<Character>(){
				public int compare(Character o1,Character o2){
					return o1.compareTo(o2);
				}
			});

			
			//출력하기
			for(char c:result)
				System.out.print(c);
			System.out.println("");
			
		}
			
		
		scanner.close();
			
	}	
}

 

 

🔑Key Point🔑

그냥 다른 포함된 것을 찾으면 안되고, 포함되었다면 그부분은 삭제해줘야 중복이 생기지 않는다.

[Java] UVa 10150 더블릿(Doublets) 문제

onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1091

 

Online Judge

10150 - Doublets 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);
		
		ArrayList<String> dictionary = new ArrayList<String>();
		String error = "No solution.\n";
		 

		while(true){
         
			String input = scanner.nextLine();
			
			if(input.equals(""))
				break;
			
			dictionary.add(input);
		}
		
		ArrayList<String> input_line = new ArrayList<String>();
		while(scanner.hasNextLine()){
			String input = scanner.nextLine();
			input_line.add(input);
		}
		String result ="";	
		for(String tmp : input_line){
			
			String[] list = tmp.split(" ");
				
			if(!dictionary.contains(list[0]) || !dictionary.contains(list[1])){
				result+=error;
				continue;
			}
			
			Queue<String> queue = new LinkedList<String>();
			int []parent = new int[dictionary.size()];
			int[] distance = new int[dictionary.size()];
			
			Arrays.fill(parent,-1);
			Arrays.fill(distance,59999);
			distance[dictionary.indexOf(list[0])]=0;
			queue.add(list[0]);
			int index=-1;
			
			while(!queue.isEmpty()){
				String now =queue.remove();
				int x = dictionary.indexOf(now);
				if(now.equals(list[1])){
					index=x;
					break;
				}
				
				for(int i=0; i<now.length(); i++){
					String copy = now;
					for(int j = 0; j < 26; j++){
						if(now.charAt(i)!='a'+j)
						{
							String next="";
							next+=copy.substring(0,i);
							next+= Character.toString((char)('a'+j));
							next+=copy.substring(i+1);
							int y = -1;
							y = dictionary.indexOf(next);
							if(y!=-1 && distance[y]==59999)
							{
								distance[y] = distance[x] + 1;
								parent[y] = x;
								queue.add(next);
							}	
						}
					}
				}		
			}
			
			if(index == -1){
				result += error;
			}
			else{
				Stack<String> bfs_stack = new Stack<String>();
				while(index!=-1)
				{
					bfs_stack.push(dictionary.get(index));
					index = parent[index];
				}
				while(!bfs_stack.isEmpty())
					result+= bfs_stack.pop() + "\n";
			}
			
			result+="\n";
		}
		System.out.print(result);
	}	
}

 

🎨 Key Point 

 이 문제가 BFS 최단경로 알고리즘을 써야하는 이유는 최단 경로를 찾으라고 하였기 때문이다.

답은 여러개가 나올 수 있으나 최단 경로를 찾으라 하였다

 

[Java] 프로그래머스 43165번 타겟 넘버 DFS

문제 설명

 

 

내 코드

class Solution {


    public int dfs(int []numbers, int target, int index, int num){
        if(index == numbers.length)
            return num == target ? 1: 0;
        else {
            return dfs(numbers,target,index+1, num+numbers[index])+dfs(numbers,target,index+1,num-numbers[index]);}
    }
    
    public int solution(int[] numbers, int target) {
        return dfs(numbers,target,0,0);
    }
    
 
}

 

 

🔑 Key Point 🔑

 

 return dfs(numbers,target,index+1, num+numbers[index])+dfs(numbers,target,index+1,num-numbers[index]);}

이부분은 +,-모든 경우의 수를 다 조사해야 되고 그것의 수를 세야 하기 때문에 +로 재귀를 썻다. 

+ Recent posts