알고리즘 with 자바

3. 문장 속 단어

yki1204 2021. 4. 10. 23:00

문제 설명

한 개의 문장이 주어지면 그 문장 속에서 가장 긴 단어를 출력하는 프로그램을 작성하세요.

문장속의 각 단어는 공백으로 구분됩니다.

단, 가장 길이가 긴 단어가 여러개일 경우 문장속에서 가장 앞쪽에 위치한 단어를 답으로 합니다.

 

첫 줄에 길이가 100을 넘지 않는 한 개의 문장이 주어집니다. 문장은 영어 알파벳으로만 구성되어 있습니다.

 

입력예시: it is time to study

출력예시: study

작성 코드

public class Test01_03 {
	
	public static void main(String[] args) {
	
		Test01_03 test03 = new Test01_03();
		System.out.println(test03.solution( "it is time to study"));
	}
    	
	public String solution(String s) {
		
		String[] arr = s.split(" ");
		
		int maxSize = Integer.MIN_VALUE;
		String result = "";
		
		for(int i = 0; i < arr.length; i++) {
			if(arr[i].length() > maxSize) {
				maxSize = arr[i].length();
				result = arr[i];
			}
		}
		
		return result;
	}
	
}

문제 풀이

split(" ")를 이용하여 maxSize를 비교를 가며 최종 String Value를 저장한다.

중요한 점은 가장 긴 길이가 여러개일 경우 앞쪽 위치한 단어를 출력해야 하므로 arr[i].length() > maxSize 에서 '>=' 로 처리하면 안되는 점이다.

 

다른 풀이 방법으로 indexOf(" ")로 원하는 앞 단어를 substring하여 길이 비교를 하고 원래 String 값에 잘라낸 이후 문자열을 넣어주면서 처리할 수 있다.

public String solution2(String s) {
	
	int maxSize = Integer.MIN_VALUE, pos;
	String result = "";
	
	while((pos = s.indexOf(" ")) != -1) {
		
		String temp = s.substring(0, pos);
		int tempSize = temp.length();
		
		if(tempSize > maxSize) {
			maxSize = tempSize;
			result = temp;
		}
		
		s = s.substring(pos+1);
	}
	
	if(s.length() > maxSize) result = s;
	
	return result;
}