forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.cpp
More file actions
28 lines (28 loc) · 756 Bytes
/
28.cpp
File metadata and controls
28 lines (28 loc) · 756 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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);
}
};