https://www.youtube.com/watch?v=izMKq3epJ-Q
Boyer-Moore algrt 关于skip的部分很重要
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
public class Solution { public int strStr(String haystack, String needle) { int[] hs = new int[256]; int h=haystack.length(); int n = needle.length(); for(int i=0;i<256;i++){ hs[i] = -1; } for(int i=0;i<n;i++){ hs[needle.charAt(i)] = i; } int sk = 0; for(int i=0;i<h-n+1;i+=sk){ sk = 0; for(int j=n-1;j>=0;j--){ if(haystack.charAt(i+j)!=needle.charAt(j)){ sk = Math.max(1,j-hs[haystack.charAt(i+j)]); break; } } if(sk==0) return i; } return -1; } }
时间: 2024-12-29 01:50:59