현재

3.문장 속 단어(Split,substring) 본문

알고리즘/기타알고리즘문제

3.문장 속 단어(Split,substring)

AAAge 2024. 3. 19. 22:59

설명

가장 긴 단어 출력(단, 가장 긴 단어의 길이가 같을 시 맨 앞의 단어를 출력한다)

예시 입력 1 

it is time to study

예시 출력 1

study

 

<힌트>

더보기

- split사용

- substring 사용

<풀이코드>

더보기
 
import java.util.Scanner;

class Main {

    public String solution(String str) {

        String answer = ""; //출력할 값 저장

        // 방법 1
        // int lengthOfWord = Integer.MIN_VALUE; // 판별할 길이 초기화 가장작은값 (-2147483648)
        // String words[] = str.split(" ");

        // for(String word : words){
        //     if(word.length() > lengthOfWord) {
        //         lengthOfWord = word.length();
        //         answer = word;
        //     }
        // }

        // 방법 2 substring 사용
        int lengthOfWord = Integer.MIN_VALUE, pos;
            while ((pos=str.indexOf(' '))!=-1) {
                String temp = str.substring(0, pos);
                int length = temp.length();
                if(length > lengthOfWord){
                    lengthOfWord = temp.length();
                    answer = temp;
                }
                str = str.substring(pos+1); //공백까지 자르고 다시 시작
                if(str.length() > length) answer = str;
            }



        return answer;
    }
   
    public static void main(String[] args){
        Main T = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine(); //한줄을 입력 받을때는 nextLine
        System.out.println(T.solution(str));
        sc.close();  
    }

}