当前位置: 首页 > 后端技术 > Python

力扣91,译码方法的Python实现

时间:2023-03-26 14:53:36 Python

题目要求:思想:动态规划,遍历字符串如果将当前字符s[i]+前一个字符s[i-1]转换成一个数,介于10和26之间,则当前字符的解码方法数是s[i-2](两个字符之前)的方法数。如果当前字符s[i]转换为数字后不为0,则将当前字符的方法号加到s[i-1](前一个字符)的方法号上。如果s[0]和s[0:2]都合法,则f(s[:])=f(s[1:])+f(s[2:])如果s[0]合法且s[如果0:2]不合法,则f(s[:])=f(s[1:])如s[0]不合法,则无编码核心代码:#dp初始化为[1,1]dp=[1,1]#遍历字符串foriinrange(1,len(s)):#当前字符的方法初始化为0res=0#如果当前的组合字符和前一个字符在10-26之间ifint(s[i-1:i+1])>=10andint(s[i-1:i+1])<=26:#的个数methodsofthecurrentcharacterisequaltothemethodsofthecurrentcharacterisequaltothemethodsofthecurrentcharacterisequaltothemethodsofthecurrentcharacterisequaltothemethodsofthecurrentstringisnot0if此处写“=”和“+=”是一样的res+=dp[i-1]#如果当前字符串不为0ifint(s[i])!=0:#然后当前字符前一个字符的方法号需要加上前一个字符的方法号res+=dp[i]#把这个结果追加到dpdp.append(res)#返回最终结果returndp[-1]ifthetestcaseis100:Thenfirsttraverseto第一个0,则10是有效字符,但0不是,所以第一个0的方法号为1遍历到第二个0,00不是有效字符,0无效,所以方法号的第二个0为0,即dp的最后一位为0,最后返回的编码结果也为0。需要注意dp中方法号与字符下标的对应关系,dp[1]对应s[0]的方法号将dp初始化为[1,1],因为默认的s[0:2]是合法的。如果合法,则将方法号添加到dp[0]。如果不合法,则不使用dp的完整代码。:类解决方案:defnumDecodings(self,s:str)->int:ifs==""orint(s[0])==0:return0dp=[1,1]foriinrange(1,len(s)):res=0如果int(s[i-1:i+1])>=10且int(s[i-1:i+1])<=26:res+=dp[i-1]如果int(s[i])!=0:res+=dp[i]dp.append(res)returndp[-1]降低了空间复杂度:classSolution:defnumDecodings(self,s:str)->int:ifs==""orint(s[0])==0:return0pre,cur=1,1foriinrange(1,len(s)):tmp=0ifint(s[i-1:i+1])<=26andint(s[i-1:i+1])>=10:tmp+=preifint(s[i])!=0:tmp+=curpre,cur=cur,tmpreturncur