-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement_strstr.py
More file actions
46 lines (35 loc) · 1.25 KB
/
implement_strstr.py
File metadata and controls
46 lines (35 loc) · 1.25 KB
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
42
43
44
45
46
# Implement strStr().
#
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
from unittest import TestCase
def strStr(haystack: str, needle: str) -> int:
diff = len(haystack) - len(needle) + 1
for i in range(diff):
if haystack[i:i + len(needle)] == needle:
return i
return -1
class TestStrStr(TestCase):
def test_with_empty_haystack_and_needle(self):
haystack = ''
needle = ''
self.assertEqual(0, strStr(haystack, needle))
def test_only_with_empty_haystack(self):
haystack = ''
needle = 'a'
self.assertEqual(-1, strStr(haystack, needle))
def test_only_with_empty_needle(self):
haystack = 'a'
needle = ''
self.assertEqual(0, strStr(haystack, needle))
def test_with_same_haystack_and_needle(self):
haystack = 'a'
needle = 'a'
self.assertEqual(0, strStr(haystack, needle))
def test_with_needle_in_haystack(self):
haystack = 'banana'
needle = 'ana'
self.assertEqual(1, strStr(haystack, needle))
def test_with_needle_not_in_haystack(self):
haystack = 'banana'
needle = 'cana'
self.assertEqual(-1, strStr(haystack, needle))