今天的題目是第3題,medium難度.
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
3. 無重復(fù)字符的最長子串
給定一個(gè)字符串,請(qǐng)你找出其中不含有重復(fù)字符的 最長子串 的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長子串是 "abc", 所以其長度為3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因?yàn)闊o重復(fù)字符的最長子串是 "b",所以其長度為1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因?yàn)闊o重復(fù)字符的最長子串是 "wke",所以其長度為3。請(qǐng)注意,你的答案必須是 子串 的長度,"pwke"是一個(gè)子序列,不是子串。
My answer:
首先對(duì)于查詢是否存在的操作我們選擇用dict來做(hash速度快), 對(duì)整個(gè)字符串進(jìn)行遍歷 用dict字典中存儲(chǔ)已經(jīng)訪問過的數(shù)據(jù). 對(duì)于未存在于dict中的元素直接添加key:value為s[i]:i; 當(dāng)遇到已經(jīng)存在的元素更新start的位置為dict[s[i]]的下一位, 因?yàn)閐ict中的值仍然保留start之前的數(shù)元素, 所以遇到的存在元素未必是有效的, 需要對(duì)start的更新值進(jìn)行判斷start = max(start, dct[s[i]] + 1). 最后更字典和最大長度即可.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = 0
max_len = 0
dct = {}
for i in range(len(s)):
if s[i] in dct:
start = max(start, dct[s[i]] + 1)
dct[s[i]] = i
max_len = max(max_len, i - start+1)
return max_len
-
字符串
+關(guān)注
關(guān)注
1文章
585瀏覽量
20603 -
字典
+關(guān)注
關(guān)注
0文章
13瀏覽量
7724 -
Start
+關(guān)注
關(guān)注
0文章
73瀏覽量
10434
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
重點(diǎn)介紹所有綜合編譯器都支持的for和repeat循環(huán)
![重點(diǎn)介紹所有綜合編譯器都支持的for和<b class='flag-5'>repeat</b>循環(huán)](https://file.elecfans.com/web2/M00/77/2E/poYBAGNjFVKAdU8mAABCI3_K8Jo656.jpg)
Labview8.5版本 關(guān)于write characters to file VI的問題
Linux Shell系列教程之Shell字符串用法
AD09多通道設(shè)計(jì)如何批量給Sheet Entry 加Repeat
將字符添加到Wildcard Characters時(shí),在屏幕上看不到這些字母怎么處理?
EFUSE_RD_REPEAT_ERR4_REG的正確地址是什么?
PCF2113x LCD控制器驅(qū)動(dòng)器數(shù)據(jù)手冊(cè)
FPGA_165B_Repeat_DigitalIO
FPGA_165A_Repeat_DigitalIO
簡談FPGA verilog中的repeat用法與例子
![簡談FPGA verilog中的<b class='flag-5'>repeat</b>用法與例子](https://file.elecfans.com/web1/M00/5C/18/o4YBAFtyc0iAPXfOAAAowveRA94224.png)
評(píng)論