zoukankan      html  css  js  c++  java
  • LeetCode #3 Longest Substring Without Repeating Characters

    LeetCode #3 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.

    Solution

    Approach #1

    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            let arr = Array(s.utf16)
            let count = arr.count
            var map: [UTF16.CodeUnit : Int] = [:]
            var i = 0
            var j = 0
            var maxLength = 0
            while i < count, j < count {
                if let index = map[arr[j]] {
                    i = max(i, index + 1)
                }
                map[arr[j]] = j
                j += 1
                maxLength = max(maxLength, j - i)
            }
            return maxLength
        }
    }
    

    Time complexity: O(n).

    Space complexity: O(m). m is the size of map.

    注意,以下代码的思路和上面完全一样,但结果是“Time Limit Exceeded”

    class Solution {
        func lengthOfLongestSubstring(_ s: String) -> Int {
            var map: [Character : Int] = [:]
            var i = 0
            var j = 0
            var maxLength = 0
            let count = s.characters.count
            while i < count, j < count {
                let endChar = s[s.index(s.startIndex, offsetBy: j)]
                if let index = map[endChar] {
                    i = max(i, index + 1)
                }
                map[endChar] = j
                j += 1
                maxLength = max(maxLength, j - i)
            }
            return maxLength
        }
    }
    

    原因是,String 以 String.Index 取下标比较耗时,不如数组的随机访问效率高。参见:http://www.cnblogs.com/silence-cnblogs/p/6877463.html

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6878223.html

  • 相关阅读:
    framework7 底部弹层popup js关闭方法
    div动画旋转效果
    面试题3
    面试题2
    CORS跨域请求[简单请求与复杂请求]
    面试题1
    nginx
    Pycharm配置支持vue语法
    Ajax在jQuery中的应用---加载异步数据
    jQuery开发入门
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6878223.html
Copyright © 2011-2022 走看看