Swift刷LeetCode 之 3- Longest Substring Without Repeating Characters-Med

17 篇文章 0 订阅
14 篇文章 0 订阅

Given a string, find the length of the longest substring without repeating characters.

给定一个字符串,查找不重复字符的最长子字符串的长度。

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

Idea:

Using a dictionary to keep track of the index of last appearance of a letter, then set a window with left and right boundry. The initial valut of left is -1 and the right is the index that goes throught the string. I used a enumaration to go therough the given string (the enumatre() function returns a sequence of pairs (nx), where n represents a consecutive integer starting at zero and x represents an element of the sequence). During each loop, the left equals to the max value between the origin left and the value of map[charactor]. The vaule of rigth minus left is the max result of longgest substring without repeating characters.

我们创建一个字典来记录每个字符在字符串中最近发生的情况。我们有一个左右标记来创建我们感兴趣的窗口。我们保证右总是大于左,所以当执行左-右时,如果左永远没有更新,它会向右索引添加1。当左可能更新时,右-左将给我们更新窗口的长度。

     func lengthOfLongestSubstring(_ s: String) -> Int {
        var map = [Character:Int]()
        var result = 0
        var left = -1
        for (right, char) in s.enumerated(){
            left = max(left,map[char] ?? -1)
            result = max(result, right - left)
            map[char] = right
           
        }
        return result
     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值