Skip to content

Commit

Permalink
leetcode larissalages#28 "implement strStr()"
Browse files Browse the repository at this point in the history
  • Loading branch information
sabrajsab authored Oct 16, 2020
1 parent c8a98ac commit 56a878c
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions leetcode/cpp/string/28.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle=="")
return 0;
double needle_hash=0, hay_hash=0;
for(int i=0;i<needle.size();++i)
{
needle_hash+=((needle[i]-'a')*pow(3,i));
}
for(int i=0;i<needle.size();++i)
{
hay_hash+=((haystack[i]-'a')*pow(3,i));
}
int k=0;
do
{
if(needle_hash==hay_hash)
return k;
if(k+needle.size()>haystack.size())
return -1;
hay_hash-=(haystack[k]-'a');
hay_hash/=3;
hay_hash+=((haystack[k+needle.size()]-'a')*pow(3,needle.size()-1));
k++;
}while(1);
}
};

0 comments on commit 56a878c

Please sign in to comment.