Skip to content

Commit 77f596e

Browse files
authored
Merge pull request larissalages#196 from sabrajsab/master
leetcode larissalages#28 "implement strStr()"
2 parents 1b12e35 + 56a878c commit 77f596e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

leetcode/cpp/string/28.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int strStr(string haystack, string needle) {
4+
if(needle=="")
5+
return 0;
6+
double needle_hash=0, hay_hash=0;
7+
for(int i=0;i<needle.size();++i)
8+
{
9+
needle_hash+=((needle[i]-'a')*pow(3,i));
10+
}
11+
for(int i=0;i<needle.size();++i)
12+
{
13+
hay_hash+=((haystack[i]-'a')*pow(3,i));
14+
}
15+
int k=0;
16+
do
17+
{
18+
if(needle_hash==hay_hash)
19+
return k;
20+
if(k+needle.size()>haystack.size())
21+
return -1;
22+
hay_hash-=(haystack[k]-'a');
23+
hay_hash/=3;
24+
hay_hash+=((haystack[k+needle.size()]-'a')*pow(3,needle.size()-1));
25+
k++;
26+
}while(1);
27+
}
28+
};

0 commit comments

Comments
 (0)