×

100DaysLeetcode(3)

96
叶孤城___
2018.04.08 21:01 字数 77

Longest Substring Without Repeating Characters

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.

Solution 1 (stupid version)

func lengthOfLongestSubstring(_ s: String) -> Int {
    guard s.count > 0 else {
      return 0
    }
    var temp = [Character: Int]()
    var count = 1
    var index = 0
    while index < s.count {
      let indexStart = s.index(s.startIndex, offsetBy: index)
      let character = s[indexStart]
      if temp[character] == nil {
        temp[character] = index
      }else {
        count = max(temp.count, count)
        if let back = temp[character] {
          index = back + 1
        }
        temp.removeAll()
        continue
      }
      index += 1
    }
    return max(count, temp.count)
  }

Solution 2 (brilliant version)

func lengthOfLongestSubstring(_ s: String) -> Int {
    var lastDuplicatePosition = -1
    var index = 0
    var maxLength = 0
    var dict = [Character: Int]()
    for c in s {
      if let lastIndex = dict[c], lastIndex > lastDuplicatePosition {
        lastDuplicatePosition = lastIndex
      }
      maxLength = max(maxLength, index - lastDuplicatePosition)
      dict[c] = index
      index += 1
    }
    return maxLength
  }
日記本
Web note ad 1