-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStrStr.py
More file actions
41 lines (33 loc) · 1021 Bytes
/
StrStr.py
File metadata and controls
41 lines (33 loc) · 1021 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
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://oj.leetcode.com/problems/implement-strstr/
"""
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
length = len(needle)
for idx in range(len(haystack) - length + 1):
# print haystack[idx:(idx+length)]
if haystack[idx:(idx + length)] == needle:
return haystack[idx:]
return None
def strStr2(self, haystack, needle):
try:
return haystack[haystack.index(needle):]
except:
return None
# TODO: implenment using KMP algorithm
def strStr3(self, haystack, needle):
pass
if __name__ == '__main__':
s = Solution()
haystack = "this is a test"
needle = "test"
print(s.strStr(haystack, needle))
print(s.strStr2(haystack, needle))
needle = "is a"
print(s.strStr(haystack, needle))
print(s.strStr2(haystack, needle))