coding test

문자열 - 백준 1543번 문서검색

ron_nie 2024. 3. 6. 18:12
728x90

1543번: 문서 검색

해석

주어진 단어가 문서에 등장하는 횟수를 구해라

접근

  1. 문서의 첫 글자부터 순회
  2. 문서의 지금 글자부터 주어진 단어와 한글자씩 비교
  3. 단어와 완전히 일치하면 개수를 올린다.
    1. 해당 단어가 등장한 이후부터 2를 반복
    2. 단어와 매치되지 않았다면 단어와 매칭되지 않았다면 다음 글자에서 2를 반복

IndexOf() 함수를 사용하면 더 쉽게 풀 수 있을 듯 하다

주의점

공백을 포함한 것을 입력받아야한다! sc.next(); 이거는 공백이 있다면 슬라이싱 해버린다!

String doc = sc.nextLine();

이렇게 받아야한다

풀이

package learnString;

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

다른 풀이 - replace()

원하는 단어를 주어진 문자열에서 전부 없애버리면?

eg. aaaaaaaa 라는 문자열에서 aaa라는 문자열을 찾고 싶을 때 해당 단어를 다 없애버리면 aa만 남게 될 것이다.

총 8개의 단어에서 주어진 3개의 단어를 빼서 2개만 남았다는 것은 6 단어가 빠진거고 이건 길이가 3짜리인 단어가 2번 등장한것과 같다.

package learnString;

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

반응형