PS

[SWEA] 1213 String

Eastplanet 2024. 1. 11. 09:43
package com.ssafy.startcamp;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Solution_D3_1213_String_오동규 {

	public static void main(String[] args) throws Exception {

		//System.setIn(new FileInputStream("1213_input.txt"));
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();

		for (int test_case = 1; test_case <= 10; test_case++) {
			int T;
			T = Integer.parseInt(in.readLine());

			sb.append("#" + test_case + " ");

			String word = in.readLine();
			String task = in.readLine();

			int wordCount = 0;
			for (int i = 0; i < task.length(); i++) {

				if (task.charAt(i) == word.charAt(0)) {
					if (word.length() + i > task.length())
						break;
					boolean flag = true;
					for (int j = i; j < i + word.length(); j++) {
						if (task.charAt(j) != word.charAt(j - i)) {
							flag = false;
							break;
						}
					}
					if (flag == true) {
						wordCount++;
					}
				}
			}

			sb.append(wordCount + "\n");
		}

		System.out.println(sb);

	}

}

 

 


			for (int i = 0; i < task.length(); i++) {

				if (task.charAt(i) == word.charAt(0)) {
					if (word.length() + i > task.length())
						break;​

탐색 범위가 task 배열 길이를 초과했을 때 중단하는 코드로 이런식으로 작성했지만 아래와 같이 하면 더 깔끔함

			for (int i = 0; i <= task.length() - word.length(); i++) {

				if (task.charAt(i) == word.charAt(0)) {