8/16 每日一題(找出最長不連續子序列)
Given a string s, find the length of the longest
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104sconsists of English letters, digits, symbols and spaces.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s)==1:
return 1
if s=='':
return 0
n=0
sub_n=1
max_len=1
res=set()
while n < len(s):
if s[n] in res:
#遇到相同時,清算
max_len=max(len(res),max_len)
res.clear() #清算
#清算後由下一項開始檢查
n=sub_n
sub_n+=1
continue#回到起始
else:
res.add(s[n])
n+=1
max_len=max(len(res),max_len)
return max_len
-------------------------參考解答
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = {}
l = 0
length = 0
for r in range(len(s)):
char = s[r]
if char in seen and seen[char] >= l:
l = seen[char] + 1
else:
length = max(length, r - l + 1)
seen[char] = r
return length
-----------------------class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l, r = 0, 0
res = 0
cs = set()
while r < len(s):
if s[r] in cs:
while s[l] != s[r]:
cs.remove(s[l])
l += 1
l += 1
else:
cs.add(s[r])
res = max(res, r - l + 1)
r += 1
return res
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁