您的位置:首页 > 其它

leetcode 第三题题目及解题思路

2017-10-13 12:20 381 查看
Longest Substring Without Repeating Characters

question:

question:
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.


answer:

def lengthOfLongestSubstring(s):
start = maxLength = 0   #开始坐标和最大长度都是0
usedChar = {}           #设置一个空字典
for i in range(len(s)):#写一个for循环,循环s的长度。
if s[i] in usedChar and start <= usedChar[s[i]]: #判断s[i]是否在字典当中并且开始坐标小于字典中对应s[i]的值,也就是s[i]中的值一定要在start后面
start = usedChar[s[i]] + 1 # 如果满足上面的条件,start等于当前的字符串i位置的值+1
else:
maxLength = max(maxLength,i - start + 1) #否则的话,返回最大的长度,maxlength,或者当前的i-起始值+1
usedChar[s[i]] = i #把usedChar[s[i]]重置为i
return maxLength


思路图解:





这个是获取最长的字符串是多少.

def findstr(str):
start = maxlength = 0
a = {}
begin = end = 0
for i in range(len(str)):
if str[i] in a and start <= a[str[i]]:
start = a[str[i]] + 1
else:
if maxlength <= i-start+1:
begin = start
end = i
maxlength = max(maxlength, i-start+1)
a[str[i]] = i
return str[begin:end+1]
print(findstr("abc1db1k2323jdkaslfjasldjkflasdfjkkladsfjlasdfkjasldkfjsdaklfjasdfjjasdkfljowejrowiej"))


参考:

https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: