Longest Substring Without Repeating Characters,longestrepeating
今天開始刷leetcode,進行一個記錄,寫的比較簡陋,見諒
Longest Substring Without Repeating Characters
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.
網上看了一個方法,很有意思,時間複雜度是o(n),首先參數m為一個列表,大小為256,可以根據ascii存放字串中每個字元對應的位置
例如:'aAb'->m[97] = 0 , m[65] = 1,m[98]=2
res記錄最大長度
start用於記錄substring的起始位置
當s[i]第一次出現也就是m[ord(s[i])]==0
或者是s[i]多次出現,但是起始位置大於之前相同字元出現的位置的時候,對res進行更新
res = max(res,i-start+1)
反之更新start位置,將start更新到出現相同字元的位置上
1 class Solution(object): 2 def lengthOfLongestSubstring(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 m = [0]*256 8 res = 0 9 start = 010 for i in range(len(s)):11 c = ord(s[i])12 if (m[c] == 0 or m[c]<start):13 res = max(res,i+1-start)14 else:15 start = m[c]16 m[c] = i+117 return res
參考資料:
[LeetCode] Longest Substring Without Repeating Characters 最長無重複子串