Notice
Recent Posts
Recent Comments
09-29 03:12
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Byeol Lo

N1786 - 찾기 본문

Algorithm/KMP

N1786 - 찾기

알 수 없는 사용자 2024. 5. 11. 17:58
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.List;
import java.util.ArrayList;


public class Main {
    static final BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
    static final BufferedWriter BW = new BufferedWriter(new OutputStreamWriter(System.out));
    static String text;
    static String pattern;

    public static void main(String[] args) throws IOException {
        List<Integer> arr;
        getInput();

        arr = solution();
        BW.write(arr.size()+ "\n");

        for(int i : arr)
            BW.write(i+"\n");

        BW.close();
        BW.close();
    }

    static void getInput() throws IOException {
        text = BR.readLine();
        pattern = BR.readLine();
    }

    static List<Integer> solution() {
        List<Integer> arr = new ArrayList<>();
        int[] pi = getPi(pattern);
        int idx = 0;
        int tlen = text.length();
        int plen = pattern.length();

        for (int i = 0; i < tlen; i++) {
            while (idx > 0 && text.charAt(i) != pattern.charAt(idx))
                idx = pi[idx-1];

            if (pattern.charAt(idx) == text.charAt(i)) {
                if (idx == plen-1) {
                    arr.add(i-idx+1);
                    idx = pi[idx];
                } else {
                    idx++;
                }
            }
        }

        return arr;
    }

    static int[] getPi(String pattern) {
       int[] pi = new int[pattern.length()];
       int tmp = pattern.length();
       int idx = 0;

       for (int i = 1; i < tmp; i++) {
           while (idx > 0 && pattern.charAt(idx) != pattern.charAt(i))
               idx = pi[idx-1];

           if (pattern.charAt(idx) == pattern.charAt(i))
               pi[i] = ++idx;
       }
       return pi;
    }

}

'Algorithm > KMP' 카테고리의 다른 글

N11585 - 속타는 저녁 메뉴  (0) 2024.05.08
N1305 - 광고  (0) 2024.05.08
Comments