본문 바로가기

Java/Java 알고리즘 인프런

[Ch.01 - String] 03. 문장 속 단어 # (+ split)

반응형
3. 문장 속 단어
 

설명

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

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

 

입력

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

출력

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

단어를 답으로 합니다.

 

예시 입력 1 

it is time to study

예시 출력 1

study

 


 

import java.util.Scanner;
  
public class Main {
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    String str=in.nextLine();
    String [] arr=str.split(" ");
    int max=Integer.MIN_VALUE;
    String answer=" ";
    for(int i=0;i<arr.length;i++){
        max=Math.max(arr[i].length(),max);
      if(max==arr[i].length()){
        answer=arr[i];
      }
    }
    System.out.println(answer);
  }
}

 

import java.util.Scanner;
  
public class Main {
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    String input1 = in.nextLine();
    System.out.println(solution(input1));
  }
  static String solution(String s){
    String[] arr = s.split(" ");
    int max=0;
    for(int i=0;i<arr.length;i++){
      if(arr[max].length()<arr[i].length())
        max=i;
    }
    
    return arr[max];
  }
}

 

1. 한줄 입력

-> kb.nextLine();

 

2. String -> String []로 [ " "로 나눠서]

-> String [] arr=str.split(" ");

 

 

+) 세련된 풀이 : indexOf() 메서드와 substring() 메서드를 이용

while((pos=str.indexOf(' '))!=-1) {
    String tmp = str.substring(0, pos);
    int len=tmp.length();
    if(len>=m) {
        m=len;
        answer=tmp;
    }
            
str=str.substring(pos+1);

 

1. tmp에 ' '전까지 잘라서 넣는다.

2. str에 자른 부분 나머지 부분을 넣는다.

3. 길이가 m보다 큰 부분을 정답으로 한다.

4. 마지막으로 자른 단어는 체크를 하지 않기 때문에, 추가로 비교를 한다.

import java.util.Scanner;
  
public class Main {
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    String input1 = in.nextLine();
    System.out.println(solution(input1));
  }
  static String solution(String s){
    String answer="";
    int m=Integer.MIN_VALUE, pos;
    
    //문자열 s에 빈칸이 존재하지 않을 때까지 반복
    //-> pos는 빈칸의 위치를 변수로 갖는다, tmp에 0부터 pos전 까지 잘라서 넣는다.
    while( (pos=s.indexOf(' '))!=-1){
      String tmp = s.substring(0, pos);
      int len=tmp.length();
      //해당 tmp의 길이가 가장 긴 문자열의 길이
      
      //해당 문자열의 길이가 더 길 때만, 가장 긴 단어로 선택
      //: 가장 긴 단어가 여러개일 경우 문장속에서 가장 앞쪽에 위치한 단어를 답으로
      if(len>m){
        m=len;
        answer=tmp;
      }
      //해당 문자열의 길이를 m에 넣어두고, m보다 큰 경우 answer를 초기화한다.
      
      s=s.substring(pos+1);
      //자른 부분 이후부터 s에 다시 넣는다.

    }
    
    //s의 길이가 m보다 크면, answer에 s를 넣는다.
    if(s.length()>m) answer=s;
    
    return answer;
  }
}

 

 

import java.util.Scanner;
  
public class Main {
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    String str = in.nextLine();
    String answer="";
    String[] arr = str.split(" ");
    int max=0;
    for(String s : arr){
      if(max<s.length()) {
        max=s.length();
        answer=s;
      }
    }
    System.out.println(answer);
  }
}

 

#split의 경우 split(" ", -1)와 같이 -1을 파라미터로 전달한다면, 공백도 포함시킨다.

반응형