From d6df4b013d9b980759fbaa692313c31350da0d37 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Thu, 2 Mar 2023 02:02:43 +0000 Subject: [PATCH 1/2] added: string compression --- .../leetcode 443 - string compression.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 14. Questions/leetcode 443 - string compression.py diff --git a/14. Questions/leetcode 443 - string compression.py b/14. Questions/leetcode 443 - string compression.py new file mode 100644 index 0000000..098546c --- /dev/null +++ b/14. Questions/leetcode 443 - string compression.py @@ -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 From 3d577429c3c9fab205f3d141d006ec3f10add45b Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Fri, 3 Mar 2023 03:31:27 +0000 Subject: [PATCH 2/2] added: index of first occurrence --- ...leetcode 28 - index of first occurrence.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 14. Questions/leetcode 28 - index of first occurrence.py diff --git a/14. Questions/leetcode 28 - index of first occurrence.py b/14. Questions/leetcode 28 - index of first occurrence.py new file mode 100644 index 0000000..e059e17 --- /dev/null +++ b/14. Questions/leetcode 28 - index of first occurrence.py @@ -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