请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
e.g.
输入: “abcabcbb”, 输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
Solution
1
2
3
4
5
6
7
8
9
10
classSolution:deflengthOfLongestSubstring(self,s:str)->int:dict={}res=tmp=0forjinrange(0,len(s)):i=dict.get(s[j],-1)# get index i, the position where s[j] existsdict[s[j]]=j# update the hash maptmp=tmp+1iftmp<j-ielsej-i# dp[j - 1] -> dp[j]res=max(res,tmp)# max(dp[j - 1], dp[j])returnres
Explanation
tmp records the length of the unrepeated substring ending with s[j].
dict records the last position where each key exists.
classSolution:# dpdeftranslateNum(self,num:int)->int:num=list(str(num))dp=[1for_inrange(0,len(num)+1)]# dp[0] == dp[1] == 1foriinrange(2,len(num)+1):# dp[i] means the sum of the approaches before num[i] (i.e., num[0] ... num[i-1])# Be careful with the index hereifint(num[i-2]+num[i-1])<26andint(num[i-2])!=0:dp[i]=dp[i-1]+dp[i-2]else:dp[i]=dp[i-1]returndp[-1]
Solution 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:# RecursiondeftranslateNum(self,num:int)->int:defrecur(arr):iflen(arr)<=1:# base casereturn1# no need to count on "01", "02", ..., "09" # no need to count on num >= 26ifint(arr[0]+arr[1])<26andint(arr[0])!=0:returnrecur(arr[1:])+recur(arr[2:])else:returnrecur(arr[1:])returnrecur(str(num))