필수개념/algorithm
백준 1543 - 문서 검색
미침
2024. 10. 20. 22:04
문서와 검색하려는 단어가 주어졌을 때,
그 단어가 최대 몇 번 중복되지 않게 등장하는지 구하는 프로그램을 작성하는 문제
A) indexOf를 이용해서 검색단어 위치를 찾아서 풀어보았다
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String first = sc.nextLine();
String second = sc.nextLine();
int count = myCountingWord(first, second);
System.out.println(count);
}
private static int myCountingWord(String text, String keyword){
int count = 0;
while(true){
int index = text.indexOf(keyword);
if(index == -1)return count;
else{
text = text.substring((keyword.length()+index));
count += 1;
}
}
}
AA) 다른 방법으로는
동일한 문자열을 모두 제거한 후에
문자열 길이 차이를 이용하여 풀어보았다
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String first = sc.nextLine();
String second = sc.nextLine();
int count = myCountingWord2(first, second);
System.out.println(count);
}
private static int myCountingWord2(String text, String keyword){
String replaced = text.replace(keyword, "");
int length = text.length() - replaced.length();
int count = length / keyword.length();
return count;
}
문자열 문제 두 번째, 아직도 백준에 익숙하지 않아
런타임 에러와 결과 이상이 발생하였지만 쉽게 풀 수 있는 문제였다
