본문 바로가기
코딩테스트/Baekjoon

[백준/JAVA] 1152번: 단어의 개수

by 희동츄루리 2023. 8. 16.
728x90

https://www.acmicpc.net/problem/1152

 

1152번: 단어의 개수

첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열

www.acmicpc.net

 

package baekjoon;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
    	
    	Scanner sc = new Scanner(System.in);   	
      String str = sc.nextLine();

      List<String> list = new ArrayList<>(Arrays.asList(str.split("\\s")));
      
      list.removeAll(Arrays.asList("", null));
      System.out.println(list.size());
      
      sc.close();
    }
}

 

  1. Scanner로 입력 받기
    1. 공백이 포함되도록 nexrLine() 사용
  2. 리스트 생성
    1. 문자열 타입으로 생성
    2. str.split("\\\\s") : 공백(\\s) 기준으로 문자열 구분
    3. 리스트 배열 생성
  3. 특정 요소가 들어간 배열 삭제
    1. list.removeAll(Arrays.asList("", null));
  4. 리스트 크기 출력