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: