- 문제 분석/해석
1. 문서의 첫 글자부터 순회
for(int i=0; i<doc.length(); i++){ // 1. 문서의 첫 글자부터 순회함
}
2. 문서의 지금 글자부터 주어진 단어와 한 글자씩 비교
for(int i=0; i<doc.length(); i++){ // 1. 문서의 첫 글자부터 순회함
boolean isMatch = true;
for(int j=0; j < word.length(); j++){ // 2. 문서의 지금 글자부터 주어진 단어와 한 글자 씩 비교
// 문서에서 확인하려는 j번째 문자의 인덱스가 문자 범위를 넘어가지 않도록 인덱스 체크
if(i+j >= doc.length() || doc.charAt(i+j) != word.charAt(j)){
isMatch = false;
break;
}
}
}
3-1. 단어와 완전히 일치하면 개수를 올림
해당 단어가 등장한 이후부터 2를 반복
for(int i=0; i<doc.length(); i++){ // 1. 문서의 첫 글자부터 순회함
boolean isMatch = true;
int count = 0;
for(int j=0; j < word.length(); j++){ // 2. 문서의 지금 글자부터 주어진 단어와 한 글자 씩 비교
// 문서에서 확인하려는 j번째 문자의 인덱스가 문자 범위를 넘어가지 않도록 인덱스 체크
if(i+j >= doc.length() || doc.charAt(i+j) != word.charAt(j)){
isMatch = false;
break;
}
}
// 3-1
if(isMatch){
count++; // 딘어와 일치하면 count 증가
i += word.length()-1; // 해당 단어가 등장한 이후부터 2를 반복
}
}
3-2. 단어와 매치되지 않았다면 다음 글자에서 2를 반복
for(int i=0; i<doc.length(); i++){ // 1. 문서의 첫 글자부터 순회함
boolean isMatch = true;
int count = 0;
for(int j=0; j < word.length(); j++){ // 2. 문서의 지금 글자부터 주어진 단어와 한 글자 씩 비교
// 문서에서 확인하려는 j번째 문자의 인덱스가 문자 범위를 넘어가지 않도록 인덱스 체크
if(i+j >= doc.length() || doc.charAt(i+j) != word.charAt(j)){
isMatch = false;
break;
}
}
// 3-1
if(isMatch){
count++; // 딘어와 일치하면 count 증가
i += word.length()-1; // 해당 단어가 등장한 이후부터 2를 반복
}else{
i++;
}
}
indexOf를 사용하면 좀 더 편하게 구현할 수 있음
int startIndex = 0; // 문자의 첫 글자에서부터 검색을 시작
int count = 0;
while(true){
int findIndex = doc.indexOf(word, startIndex);
// [indexOf]
// doc 문자열의 startIndex부터 처음으로 등장하는 word 문자열을 찾음
// 찾았다면 일치하는 시작 인덱스를 반환, 없으면 -1을 반환
if(findIndex < 0) break; // 찾지 못하면 검색 종료
startIndex = findIndex + word.length();
count++;
}
replace를 사용해서도 풀 수 있음
String replaced = doc.replace(word, "");
int length = doc.length()-replaced.length();
int count = length / word.length();
System.out.println(count);
- 내 코드
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String doc = sc.nextLine();
String word = sc.nextLine();
int count = 0;
for(int i=0; i<=doc.length()-word.length();){
String slice_doc = doc.substring(i, i+word.length());
if(slice_doc.equals(word)){
count++;
i+=word.length();
}else{
i++;
}
}
System.out.println(count);
}
}
- 핵심 개념 / 알고리즘:
- 문자열 함수
- substring
- equals
- charAt
- indexOf
- 문자열 함수
- 개선점 / 주의할 점:
- word.length()를 더할지, word.length()-1을 더할지 판단
- indexOf를 사용하면 더 간편하게 풀 수 있음
'스터디 > 알고리즘' 카테고리의 다른 글
[백준 13223] 소금 폭탄 (0) | 2025.07.30 |
---|---|
[백준 1157] 단어 공부 (0) | 2025.07.30 |
[백준 1919] 애너그램 만들기 (0) | 2025.07.30 |
[백준 2744] 대소문자 바꾸기 (0) | 2024.08.06 |
[백준 11655] ROT13 (0) | 2022.06.21 |