본문 바로가기
코딩테스트

백준 1543 - 문서 검색

by SuperDT 2024. 10. 20.

문서와 검색하려는 단어가 주어졌을 때, 

그 단어가 최대 몇 번 중복되지 않게 등장하는지 구하는 프로그램을 작성하는 문제

 

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;
    }

 

 

문자열 문제 두 번째, 아직도 백준에 익숙하지 않아

런타임 에러와 결과 이상이 발생하였지만 쉽게 풀 수 있는 문제였다

 

'코딩테스트' 카테고리의 다른 글

백준 13223 - 소금폭탄  (0) 2024.10.27
[구름] 발전기 (python)  (0) 2024.10.27
[구름] 딱지놀이  (0) 2024.10.17
[프로그래머스] 있었는데요 없었습니다  (0) 2024.09.22
백준 1157 - 단어공부  (0) 2024.09.15