forked from diwu/LeetCode-Solutions-in-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedium_003_Longest_Substring_Without_Repeating_Characters.swift
58 lines (49 loc) · 2.11 KB
/
Medium_003_Longest_Substring_Without_Repeating_Characters.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
#3 Longest Substring Without Repeating Characters
Level: medium
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
Inspired by @heiyanbin at https://oj.leetcode.com/discuss/6168/my-o-n-solution
*/
private extension String {
/*
Ref: http://oleb.net/blog/2014/07/swift-strings/
"Because of the way Swift strings are stored, the String type does not support random access to its Characters via an integer index — there is no direct equivalent to NSStringʼs characterAtIndex: method. Conceptually, a String can be seen as a doubly linked list of characters rather than an array."
By creating and storing a seperate array of the same sequence of characters,
we could hopefully achieve amortized O(1) time for random access.
*/
func randomAccessCharactersArray() -> [Character] {
return Array(self.characters)
}
}
struct Medium_003_Longest_Substring_Without_Repeating_Characters {
// t = O(N), s = O(1)
static func longest(_ s: String) -> Int {
let charArr = s.randomAccessCharactersArray()
let len = charArr.count
if len <= 1 {
return len
} else {
var tmpMaxLen = 1
var maxLen = 1
var hashMap = Dictionary<Character, Int>()
hashMap[charArr[0]] = 0
for i in 1..<len {
if let lastPosition = hashMap[charArr[i]] {
if lastPosition < i - tmpMaxLen {
tmpMaxLen += 1
} else {
tmpMaxLen = i - lastPosition
}
} else {
tmpMaxLen += 1
}
hashMap[charArr[i]] = i
if tmpMaxLen > maxLen {
maxLen = tmpMaxLen
}
}
return maxLen
}
}
}