[SW Expert Academy] 1213. String- Java

2019. 8. 29. 15:08프로그래밍/알고리즘

반응형

[SWEA] 1213. [S/W 문제해결 기본] 3일차 - String

 

문제

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14P0c6AAUCFAYi&categoryId=AV14P0c6AAUCFAYi&categoryType=CODE

 

 

 

문제풀이


1. indexOf( String str, int fromIndex )를 이용하여 특정문자열을 찾는다. 
   -fromIndex 위치부터 str문자가 있는 위치를 검색하게 된다.

 

2. Scanner함수의 next()와 nextLine()

   쉬워서 바로 풀릴 줄 알았는데 시간초과가 떠서 알아보니 nextLine()으로 문자열을 받고 있어서 였다.
   -next() 
    공백을 기준으로 입력받는다. ( 띄어쓰기가 기준이 된다.)
   -nextLine() 
     라인을 기준으로 입력받는다. ( 개행문자'\n' 가 기준이 된다.)

 

 

 

전체소스                                           
import java.util.*;

public class Solution{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        for(int t =1; t <=10; t++)
        {
            int tc		= sc.nextInt();
            String word		= sc.next();
            String str		= sc.next();
            
            int cnt	  = 0;
            int fromIndex = -1;
            while((fromIndex = str.indexOf( word , fromIndex +1)) >= 0)
            {
                cnt ++;
            }
            System.out.println("#" + tc + " " + cnt);
        }
    }
}
반응형