Skip to content

feat: Add num of ways to split string algorithm #3741

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

Closed
wants to merge 7 commits into from
Closed
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
47 changes: 47 additions & 0 deletions dynamic_programming/decode_ways.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
A message containing letters from A-Z is being encoded to numbers using the
following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits,
determine the total number of ways to decode it.
"""

def num_decodings(s: str):
"""
>> num_decodings("12")
2
>> num_decodings("226")
3
"""
if not s or int(s[0]) == 0:
return 0

last = 1
second_last = 1

for i in range(1, len(s)):
# 0 is a special digit since it does not
# correspond to any alphabet but can be
# meaningful if preceeded by 1 or 2

if s[i] == "0":
if s[i-1] in {"1", "2"}:
curr = second_last
else:
return 0
elif 11 <= int(s[i-1:i+1]) <= 26:
curr = second_last + last
else:
curr = last

last, second_last = curr, last
return last


if __name__ == "__main__":
import doctest

doctest.testmod()
44 changes: 44 additions & 0 deletions strings/num_splits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
You are given a string s, a split is called good if you can split s into
2 non-empty strings p and q where its concatenation is equal to s and
the number of distinct letters in p and q are the same.
Return the number of good splits you can make in s.
"""
from collections import Counter, defaultdict

def num_splits(self, s: str):
"""
>> num_splits("aacaba")
2
>> num_splits("abcd")
1
>> num_splits("aaaaa")
4
"""
ans = 0
rightSplit = Counter(s)
leftSplit = defaultdict(int)

leftCount = 0
rightCount = len(rightSplit)

for ch in s:
rightSplit[ch] -= 1
leftSplit[ch] += 1

if rightSplit[ch] == 0:
rightCount -= 1

leftCount = len(leftSplit)

if leftCount == rightCount:
ans += 1

return ans


if __name__ == "__main__":
import doctest

doctest.testmod()