본문 바로가기

CodingTest Practice

[인프런] 문장 속 단어

문장 속 단어

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

 

■ 문제 풀이

1) 입력 설명
- 문장 속의 각 단어는 공백으로 구분
- 문장의 길이가 100이 넘지 않는 한 개의 문장이 주어진다.
- 문장은 영어 알파벳으로만 구성

2) 출력 설명
- 첫 줄에 가장 긴 단어를 출력
- 가장 긴 단어가 여러개일 경우 문장 속에서 가장 앞쪽에 위치한 단어를 답으로 반환

3) 테스트
it is time to study -> study를 반환

4) 문제 풀이
- 첫번째 solution에서는 String 클래스의 split() 메서드를 이용하여 문제를 해결
- 두번째 solution에서는 String 클래스의 indexOf() 메서드와 substring() 메서드를 이용해서 문제 해결
- 두번째 solution의 경우, 마지막 if문은 띄어쓰기가 모두 끝난 후 마지막 문장의 길이와 max값의 비교를 통해 제일 긴 문장을 찾는 과정

 

import java.util.Arrays;
import java.util.Scanner;

public class Find {

    public String solution(String input) {
        String answer = "";
        String[] split = input.split(" ");
        int max = Integer.MIN_VALUE;    //최대값 초기화

        for (String s : split) {
            int len = s.length();
            if (max < len) {
                max = len;
                answer = s;
            }
        }

        return answer;
    }

    public String solution2(String input) {
        String answer = "";
        int max = Integer.MIN_VALUE;
        int pos;

        while ((pos = input.indexOf(" ")) != -1) {
            String s = input.substring(0, pos);
            int len = s.length();
            if (len > max) {
                max = len;
                answer = s;
            }
            // input string을 띄어쓰기를 기준으로 잘라준다.
            input = input.substring(pos + 1);
        }

        if (input.length() > max) {
            answer = input;
        }

        return answer;
    }

    public static void main(String[] args) {
        Find find = new Find();
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        System.out.println(find.solution(input));
        System.out.println(find.solution2(input));
        return;
    }
}

 

'CodingTest Practice' 카테고리의 다른 글

[인프런] 특정 문자 뒤집기  (0) 2022.03.31
[인프런] 단어 뒤집기  (0) 2022.03.30
[인프런] 대소문자 변환  (0) 2022.03.29
[인프런] 문자 찾기 - 문자열  (0) 2022.03.28
[프로그래머스] K번째수  (0) 2022.03.28