Skip to content

Commit 21975fa

Browse files
committed
Add 28
1 parent a494d96 commit 21975fa

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Solutions for https://leetcode.com/ algorithmic problems.
1515
| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [0020](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0020.py) |
1616
| [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [0026](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0026.py) |
1717
| [Remove Element](https://leetcode.com/problems/remove-element/) | [0027](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0027.py) |
18+
| [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | [0028](https://github.com/varvarvarvar/leetcode/blob/master/solutions/0028.py) |
1819
| [Sort Colors](https://leetcode.com/problems/sort-colors/) | [0075](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0075.py) |
1920
| [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [0125](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0125.py) |
2021
| [Rotate Array](https://leetcode.com/problems/rotate-array/) | [0189](https://github.com/varvara-krasavina/leetcode/blob/master/solutions/0189.py) |

solutions/0028.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""Return the index of the first occurrence of needle in haystack,
2+
or -1 if needle is not part of haystack.
3+
4+
For the purpose of this problem, we will return 0 when needle is an empty string.
5+
6+
"""
7+
8+
9+
class Solution:
10+
def strStr(self, haystack: str, needle: str) -> int:
11+
12+
if not needle:
13+
return 0
14+
15+
if len(needle) > len(haystack):
16+
return -1
17+
18+
if len(needle) == len(haystack):
19+
if needle == haystack:
20+
return 0
21+
return -1
22+
23+
for i in range(len(haystack) - len(needle) + 1):
24+
25+
first_j = i
26+
27+
for j in range(len(needle)):
28+
29+
if first_j == len(haystack):
30+
break
31+
32+
if haystack[first_j] != needle[j]:
33+
break
34+
35+
first_j += 1
36+
37+
if first_j - i == len(needle):
38+
return i
39+
40+
return -1
41+
42+
43+
if __name__ == "__main__":
44+
45+
sol = Solution()
46+
47+
assert sol.strStr("aaa", "aaaa") == -1
48+
assert sol.strStr("mississippi", "issip") == 4
49+
assert sol.strStr("hello", "ll") == 2
50+
assert sol.strStr("aaa", "aaa") == 0
51+
assert sol.strStr("a", "a") == 0
52+
assert sol.strStr("aaa", "aaa") == 0
53+
assert sol.strStr("ba", "a") == 1
54+
assert sol.strStr("aaaaa", "bba") == -1
55+
assert sol.strStr("", "") == 0

0 commit comments

Comments
 (0)