-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path567-permutation-in-string.swift
29 lines (26 loc) · 1.07 KB
/
567-permutation-in-string.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
class Solution {
func checkInclusion(_ s1: String, _ s2: String) -> Bool {
_checkInclusion(Array(s1), Array(s2))
}
private func _checkInclusion(_ s1: [Character], _ s2: [Character]) -> Bool {
guard s1.count <= s2.count else { return false }
var diffMap = [Character: Int]()
var diff = 0
for tail in 0..<s2.count {
let s = tail < s1.count ? s1 : s2
let head = tail < s1.count ? tail : tail - s1.count
let oldHeadValue = diffMap[s[head]] ?? 0
let newHeadValue = oldHeadValue + 1
diffMap[s[head]] = newHeadValue
if oldHeadValue == 0 { diff += 1 }
if newHeadValue == 0 { diff -= 1 }
let oldTailValue = diffMap[s2[tail]] ?? 0
let newTailValue = oldTailValue - 1
diffMap[s2[tail]] = newTailValue
if oldTailValue == 0 { diff += 1 }
if newTailValue == 0 { diff -= 1 }
if tail >= (s1.count - 1) && diff == 0 { break }
}
return diff == 0
}
}