Skip to content

added leetcode questions #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 14. Questions/leetcode 28 - index of first occurrence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 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/
# sliding window to match each character of the haystack with the needle; no slices.

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# ----- using regex -----
# if needle == '':
# return 0

# import re
# match = re.search(needle, haystack)
# return match.start() if match else -1

# ----- using sliding windows -----
ptrL, ptrR = 0, 0
N_needle, N_haystack = len(needle), len(haystack)
while ptrR < N_haystack:
if haystack[ptrR] == needle[ptrR - ptrL]:
ptrR += 1
if ptrR - ptrL > N_needle - 1:
return ptrL
else:
ptrR = ptrL + 1
ptrL += 1

return -1
22 changes: 22 additions & 0 deletions 14. Questions/leetcode 443 - string compression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# string compression | leetcode 443 | https://leetcode.com/problems/string-compression/
# sliding window to keep track of a char's occurence

class Solution:
def compress(self, chars: list[str]) -> int:
ptrL, ptrR = 0, 0
total = 0
chars += " "

while ptrR < len(chars):
if chars[ptrL] != chars[ptrR]:
chars[total] = chars[ptrL]
total += 1
group = ptrR - ptrL
if group > 1:
for x in str(group):
chars[total] = x
total += 1
ptrL = ptrR
ptrR += 1

return total