찌니의 프로그래밍 삼매경

[알고리즘] 문자열 문장 속 단어 본문

알고리즘

[알고리즘] 문자열 문장 속 단어

zzI니☆ 2022. 10. 19. 11:02
728x90

👀 한 개의 문장이 주어지면 그 문장 속에서 가장 긴 단어를 출력하는 프로그램을 작성하세요. 문장속의 각 단어는 공백으로 구분됩니다.

입력

문장은 영어 알파벳으로만 구성되어 있습니다.

it is time to study

출력

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

study

import java.util.Scanner;

// 문장 속 단어
public class Main {
    public static String solution(String str) {
        String[] words = str.split(" ");
        String answer = "";
        int maxLen = 0;
        for (String x : words) {
            if (maxLen < x.length()) {
                maxLen = x.length();
                answer = x;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        sc.close();
        System.out.println(solution(str));
    }
}
728x90
Comments