leetcode 第三题题目及解题思路
2017-10-13 12:20
381 查看
Longest Substring Without Repeating Characters
思路图解:
参考:
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/
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/
相关文章推荐
- [LeetCode] Word Break 解题思路
- leetCode 66.Plus One (+1问题) 解题思路和方法
- [LeetCode] 74. Search a 2D Matrix 解题思路
- LeetCode Weekly Contest 41解题思路
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
- leetCode 33.Search in Rotated Sorted Array(排序旋转数组的查找) 解题思路和方法
- leetCode 50.Pow(x, n) (x的n次方) 解题思路和方法
- leetcode小白解题记录——第三题
- leetCode 83.Remove Duplicates from Sorted List(删除排序链表的重复) 解题思路和方法
- [LeetCode] 219. Contains Duplicate II 解题思路
- LeetCode Weekly Contest 27解题思路
- [LeetCode] Distinct Subsequences 解题思路
- [LeetCode] 86. Partition List 解题思路
- [LeetCode] Decode Ways 解题思路
- [LeetCode] 28. Implement strStr() 解题思路
- [LeetCode] 3Sum 解题思路
- [LeetCode] 3. Longest Substring Without Repeating Characters 解题思路
- [LeetCode] 205. Isomorphic Strings 解题思路 - Java
- leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法
- leetCode 64.Minimum Path Sum (最短路) 解题思路和方法