* Java 8 기준
[백준/Java] 문서 검색 1543
1543번: 문서 검색
세준이는 영어로만 이루어진 어떤 문서를 검색하는 함수를 만들려고 한다. 이 함수는 어떤 단어가 총 몇 번 등장하는지 세려고 한다. 그러나, 세준이의 함수는 중복되어 세는 것은 빼고 세야 한
www.acmicpc.net
문제: 주어진 단어가 문서에 등장하는 횟수
풀이
- 문서의 첫 글자부터 순회한다.
- 문서의 지금 글자부터 주어진 단어와 한글자씩 비교한다.
- 단어와 완전히 일치하면 개수를 올린다.
해당 단어가 등장한 이후부터 2를 반복한다. - 단어와 매치되지 않았다면 다음 글자에서 2를 반복한다.
코드
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 count = 0;
int startIndex = 0;
while (true) {
int findIndex = doc.indexOf(word, startIndex);
if (findIndex < 0)
break;
count++;
startIndex = findIndex + word.length();
}
System.out.println(count);
}
}
// String.indexOf(int ch, int fromIndex) fromIndex부터 ch 문자가 나타나는 가장 첫 인덱스
// fromIndex부터 ch 문자가 나타나는 가장 첫 인덱스, 못찾으면 -1을 반환한다.
// while 반복문과 if 반복문
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 count = 0;
for (int i = 0; i < doc.length(); i++) {
boolean isMatch = true;
for (int j = 0; j < word.length(); j++) {
if (i + j >= doc.length() || doc.charAt(i + j) != word.charAt(j)) {
isMatch = false;
break;
}
}
if (isMatch) {
count++;
i += word.length() -1;
}
}
System.out.println(count);
}
}
// i += word.length() -1 에 주의
// for 반복문에서는 i++로 자동으로 1씩 더해지므로
// word.length()-1을 한 값에 반복문으로 +1 더해져야 word.length()만큼 늘어난다.
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();
String replaced = doc.replace(word, "");
int length = doc.length() - replaced.length();
int count = length / word.length();
System.out.println(count);
}
}
// String replace(CharSequence target, CharSequence replacement)
// 문자열 중에서 target문자열을 새로운 문자열 replacement로 모두 바꾼 문자열을 반환한다.
// ababababa
// aba
// System.out.println(replaced);
// bba (aba를 공백으로 바꿨으므로 남은 bba가 반환된다.)
'알고리즘' 카테고리의 다른 글
[BAEKJOON 백준 / Java] 소금 폭탄 13223 (1) | 2023.06.03 |
---|