Longest Substring Without Repeating Characters,longestrepeating

來源:互聯網
上載者:User

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 最長無重複子串

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.