public int search(String text) {
        int N = text.length();
        if (N < patternLength) return N; //text cannot be smaller than pattern.
        long textHash = hash(text, patternLength);

        //check for match at offset 0.
        if (patternHash == textHash && check(text, 0)) {
            return 0;
        }

        for (int i=patternLength; i<N; i++) {
            textHash = (textHash + Q - RM*text.charAt(i-patternLength) % Q) % Q;
            textHash = (textHash*R + text.charAt(i)) % Q;

            int offset = i-patternLength+1;
            if ((patternHash == textHash) && check(text, offset)) {
                return offset;
            }
        }
        return N;
    }