LeetCode 刷題筆記 - 3. 無重複字符的最長子串

難度:

中等swift

描述:

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。bash

示例

1:
輸入: "abcabcbb"  
輸出: 3  
解釋: 由於無重複字符的最長子串是 "abc",因此其長度爲 3。
複製代碼
2:
輸入: "bbbbb"  
輸出: 1  
解釋: 由於無重複字符的最長子串是 "b",因此其長度爲 1。
複製代碼
3:
輸入: "pwwkew"  
輸出: 3  
解釋: 由於無重複字符的最長子串是"wke",因此其長度爲 3。
    請注意,你的答案必須是 子串 的長度,"pwke"是一個子序列,不是子串。
複製代碼

來源:力扣(LeetCode) 連接:leetcode-cn.com/problems/lo… 著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。網絡


語言:

swiftui

解析:

這題要找到最長子串,我打算用兩個遊標來尋找。一樣,我採用字典的方式將出現過的字符存下來,字典的結構爲[Character : Int]key爲對應字符,value爲該字符所在下標。
咱們在遍歷字符串每一個字符的時候,將出現的字符存儲下來,若是發現了相同且存在的字符,證實該字符上次出現的位置不可用,因此將起始遊標的位置startIndex移動到這個字符上次出現位置的後面。
好比字符串abcdebf,起始遊標和終止遊標都爲0,開始遍歷操做,終止遊標endIndex向後移動,在遍歷到第5個字符b的時候,b在字典中已經存在了,且下標爲1,則該位置不可用,起始遊標startIndex變爲2,則當前遊標區間內的字符串爲cdeb。以此類推。
咱們爲了找最長的字符串,因此設置maxLength記錄最大長度,在遊標移動的時候,去判斷賦值。spa

代碼以下:code

class Solution {
    func lengthOfLongestSubstring(_ s: String) -> Int {
        if s.count == 0 {
            return 0
        }
        var maxLength = 0, startIndex = 0, endIndex = 0
        var stringMap = [Character : Int]()
        let stringArray = Array(s)
        
        for index in 0...s.count - 1 {
            let character = stringArray[index]
            endIndex += 1
            if let start = stringMap[character] {
                startIndex = startIndex > start + 1 ? startIndex : start + 1
            }
            stringMap[character] = index
            maxLength = maxLength > endIndex - startIndex ? maxLength : endIndex - startIndex
        }
        return maxLength
    }
}
複製代碼

總結

遊標的使用。leetcode

相關文章
相關標籤/搜索