Algorithm/문제

3.문장 속 단어

챛채 2023. 5. 10. 16:53

 

 

1. split() 사용

import java.util.Scanner;

public class Main {
   public String solution(String str) {
       String answer=""; //문장에서 가장 긴 단어
       int m = Integer.MIN_VALUE; //음수가 아니기에 0으로 초기화해도 됨
       String[] s = str.split(" ");
       for(String x : s){
           int len=x.length();
           if(len>m){
               m=len;
               answer =x;
           }
       }

       return answer;
   }

   public static void main(String[] args){
       Main T = new Main();
       Scanner kb = new Scanner(System.in);
       String str = kb.nextLine();
       System.out.print(T.solution(str));
   }
}

 

 

2. indexOf(), substring() 사용

import java.util.Scanner;

public class Main {
   public String solution(String str) {
       String answer=""; //문장에서 가장 긴 단어
       int m = Integer.MIN_VALUE, pos; //음수가 아니기에 0으로 초기화해도 됨
       while((pos=str.indexOf(' '))!=-1){ //띄어쓰기 발견 못하면 -1리턴, 발견하면 인덱스 번호 return
           //첫번째 띄어쓰기 index->2
           String tmp = str.substring(0, pos); //index 0부터 pos전까지
           int len=tmp.length();
           if (len > m) { //len>=m 하면 뒤 쪽 단어가 선택될 수 있음
               m=len;
               answer=tmp;
           }
           str=str.substring(pos + 1); //pos+1부터 끝까지 보냄
           //pos는 It뒤의 띄어쓰기 부분 -> is~study까지로 str변경
           //여기까지만 하면 마지막 단어인 study까지 못가고 time으로 결과가 나옴

       }
       //마지막 단어 처리
       if(str.length()>m) answer=str; //마지막 단어의 길이가 m보다 크면 answer이 str로 바뀌어야함

       return answer;
   }

   public static void main(String[] args){
       Main T = new Main();
       Scanner kb = new Scanner(System.in);
       String str = kb.nextLine();
       System.out.print(T.solution(str));
   }
}

마지막 단어 처리하는 부분 주의!