classSolution{ publicintstrStr(String haystack, String needle){ if (haystack == null || needle == null || haystack.length() < needle.length()) { return -1; } if (needle.length() == 0) { return0; } int len = needle.length(); int MAX = 1000000; int MOD = 31; int target = 0; int cur = 0; int HIGH = 1; for (int i = 0; i < len; i++) { target = ((target * 31) % MOD + needle.charAt(i)) % MOD; HIGH = (HIGH * 31) % MOD; } for (int i = 0; i < haystack.length(); i++) { cur = ((cur * 31) % MOD + haystack.charAt(i)) % MOD; if (i < len - 1) { continue; } if (cur == target && haystack.substring(i - len + 1, i + 1).equals(needle)) { return i - len + 1; } cur = (cur - (haystack.charAt(i - len + 1) * HIGH) % MOD) % MOD; } return -1; } }