https://www.acmicpc.net/problem/1543
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1 = br.readLine();
String str2 = br.readLine();
int count =0;
while(str1.contains(str2)){
str1 = str1.replaceFirst(str2,"_");
count++;
}
System.out.println(count);
}
}
처음에는 일치하는 부분을 ""으로 바꾸었는데
aababa
aba
(a___ba 공백으로 replace하면 aba가 생긴다.)
같은 반례가 있어
문제에서 주어지지않는 문자인 "_" 로 바꾸어 주었다.
모범답
import java.util.Scanner;
class Main
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String doc = sc.nextLine();
String word = sc.nextLine();
int startIndex = 0;
int count = 0;
while (true) {
int findIndex = doc.indexOf(word, startIndex);
if (findIndex < 0)
break;
startIndex = findIndex + word.length();
count++;
}
System.out.println(count);
}
}
'Problem Solving > 구현' 카테고리의 다른 글
BOJ10158 개미 (0) | 2024.01.29 |
---|---|
BOJ13223 소금폭탄 (0) | 2024.01.24 |
BOJ1919 애너그램만들기 (0) | 2024.01.24 |
BOJ2744 대소문자 바꾸기 (0) | 2024.01.24 |
자바 문법 - 진수 바꾸기 (3진법뒤집기) (0) | 2023.11.22 |