infogulch

Untitled

Apr 3rd, 2012
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. // with hash functions from http://pastebin.com/nb51hyvd you could do substring matching like this: (pseudocode)
  2.  
  3. // features:
  4. // ** no extra data storage, in fact needle can be freed immediately (if you trust the hash)
  5. // ** only one loop through haystack, with each loop only consisting of 2 small hash operations
  6.  
  7. int InStr(String haystack, String needle) {
  8.     int needleHash = Hash(needle);
  9.     int hash = Hash(SubString(haystack, 0, needle.length));
  10.     if (hash == needleHash)
  11.         return 0;
  12.     for(int i = 0, j = needle.length; j < haystack.length; i++, j++)
  13.     {
  14.         hash = Hash_Remove(hash, haystack[i]); // remove the first
  15.         hash = Hash_Add(hash, haystack[j]);  // add the next
  16.         if (hash == needleHash)
  17.             return i + 1;
  18.     }
  19.     return -1;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment