Skip to content

Commit b25024c

Browse files
authoredMar 6, 2023
Merge pull request #23 from mihirs16/master
added leetcode questions
2 parents 484e08a + 3d57742 commit b25024c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# find the index of the first occurrence of a string | leetcode 28 | https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
2+
# sliding window to match each character of the haystack with the needle; no slices.
3+
4+
class Solution:
5+
def strStr(self, haystack: str, needle: str) -> int:
6+
# ----- using regex -----
7+
# if needle == '':
8+
# return 0
9+
10+
# import re
11+
# match = re.search(needle, haystack)
12+
# return match.start() if match else -1
13+
14+
# ----- using sliding windows -----
15+
ptrL, ptrR = 0, 0
16+
N_needle, N_haystack = len(needle), len(haystack)
17+
while ptrR < N_haystack:
18+
if haystack[ptrR] == needle[ptrR - ptrL]:
19+
ptrR += 1
20+
if ptrR - ptrL > N_needle - 1:
21+
return ptrL
22+
else:
23+
ptrR = ptrL + 1
24+
ptrL += 1
25+
26+
return -1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# string compression | leetcode 443 | https://leetcode.com/problems/string-compression/
2+
# sliding window to keep track of a char's occurence
3+
4+
class Solution:
5+
def compress(self, chars: list[str]) -> int:
6+
ptrL, ptrR = 0, 0
7+
total = 0
8+
chars += " "
9+
10+
while ptrR < len(chars):
11+
if chars[ptrL] != chars[ptrR]:
12+
chars[total] = chars[ptrL]
13+
total += 1
14+
group = ptrR - ptrL
15+
if group > 1:
16+
for x in str(group):
17+
chars[total] = x
18+
total += 1
19+
ptrL = ptrR
20+
ptrR += 1
21+
22+
return total

0 commit comments

Comments
 (0)
Failed to load comments.