[java] SWEA - String

세상을 바꾸는 개발자·2023년 5월 20일
0

[문제링크 - SWEA - String] https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14P0c6AAUCFAYi

  • for문을 돌리며 같은지 확인할 때, i<=str.length()-word.length() 부분을 주의해야 한다.
  • substring을 사용할 때 i+word.length()를 하면 해당 길이의 -1일만큼 더해지므로 고려해야 한다.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
	public static void main(String[] args) throws IOException{
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedReader br = new BufferedReader(new FileReader("input1213.txt"));
		StringBuilder sb = new StringBuilder();
		
		for(int t=1; t<=10; t++) {
			int c = Integer.parseInt(br.readLine());
			String word = br.readLine();
			String str = br.readLine();
			
			int cnt = 0;
			for(int i=0; i<=str.length()-word.length(); i++) {
				String a = str.substring(i, i+word.length());
				if(a.equals(word)) {
					cnt++;
				}
			}
			
			sb.append("#" + t + " " + cnt + "\n");
		}
		
		System.out.println(sb);
	}
}
profile
초심 잃지 않기

0개의 댓글

관련 채용 정보