Skip to content

Instantly share code, notes, and snippets.

@mattf
Created January 11, 2020 01:53
Show Gist options
  • Save mattf/5d5c0c9a098cc6dbfa98e4194dbbc873 to your computer and use it in GitHub Desktop.
Save mattf/5d5c0c9a098cc6dbfa98e4194dbbc873 to your computer and use it in GitHub Desktop.
def numDecodings(s: str) -> int:
if(not s):return 1
elif(len(s)==1):
if(s=="0"):return 0
else:return 1
if(s[0]=="0"):return 0
prev=1
cur=0 if s[1]=="0" else 1
if(int(s[:2])<=26): cur+=1
for i in range(2,len(s)):
if(s[i]!="0"):temp=cur
else:temp=0
if(s[i-1]!="0" and int(s[i-1:i+1])<=26):temp+=prev
prev,cur=cur,temp
return cur
================================================================================
from functools import lru_cache
@lru_cache(maxsize=None)
def numDecodings(self, s: str) -> int:
if not s:
return 1
single = 0
if '1' <= s[0] and s[0] <= '9':
single = self.numDecodings(s[1:])
double = 0
if 10 <= int(s[:2]) and int(s[:2]) <= 26:
double = self.numDecodings(s[2:])
return single + double
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment