美文网首页
100DaysLeetcode(3)

100DaysLeetcode(3)

作者: 叶孤城___ | 来源:发表于2018-04-08 21:01 被阅读772次

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
  }

相关文章

  • 100DaysLeetcode(3)

    Longest Substring Without Repeating Characters Given a st...

  • 100DaysLeetcode(1)

    Add Two Numbers You are given two non-empty linked lists ...

  • 100DaysLeetcode(2)

    Add Two Numbers Given an array of integers, return indice...

  • 恶意文件夹

    【%你的iapp在这里哦/恭喜你找到了/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3...

  • 3+3+3

    九年了,不曾去过,马路那边的刘家村。唱戏,小路~抓蝌蚪,洗衣服,捞水草,漩涡~种满菜的田地,养着奶牛的茅草屋,充满...

  • 3/3

    郭一博 刘佐千 李文浩 王天聪 柳絮 刘全利 李明东

  • 3/3

  • if(a==3) or if(3==a)

    记得刚写程序那会儿,遇到 if else 的条件判断逻辑,基本都会这样写:if(a==3) 为什么呢? 因为自然...

  • 3/3

    原先我是为了他留长头发,现在他的女朋友剪了短发,他说随她去,都好。 原先她卑微付出真心为他,现在她是个被宠溺的幸福...

  • 3/3

    夜月再至,只剩着静谧和四寂与我作伴, 呼啸而过,耳畔又闻过车马还川流不息, 旧亿渐入,也始终囚于泯然其细枝末节。 ​​​

网友评论

      本文标题:100DaysLeetcode(3)

      本文链接:https://www.haomeiwen.com/subject/uuwmhftx.html