LeetCode Algorithms3: Longest substring without repeating characters(in swift)

来源:互联网 发布:淘宝官方活动报名 编辑:程序博客网 时间:2024/05/29 16:56

LeetCode algorithms 3

Problem:
Give a string, find the length of the longest substring without repeating characters.
Examples:
Give "abcabcbb", the answer is "abc",which the length is 3.
Given "pwwkew",the answer is "wke",with the length is 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Code( in swift ):

class Solution {    func lengthOfLongestSubstring(s: String) -> Int{        var j = 0, ret = 0        var charAt = [Int](count:256, repeatedValue:0)        if s.isEmpty {            return 0        }        var i = 0        for c in s.utf8{            if charAt[Int(c)]>j{                if i-j>ret{                    ret = i-j                }                j = charAt[Int(c)]            }            charAt[Int(c)] = i+1            i+=1        }        return (i-j>ret) ? (i-j) : ret    }}

Time complexity: O(n), for-loop will iterate n times.
Space complexity: O(m), m is the size of the longest substring.

0 0
原创粉丝点击