forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestDistanceToACharacter.swift
More file actions
35 lines (27 loc) · 961 Bytes
/
ShortestDistanceToACharacter.swift
File metadata and controls
35 lines (27 loc) · 961 Bytes
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
/**
* Question Link: https://leetcode.com/problems/shortest-distance-to-a-character/
* Primary idea: Iterate through left and right to get min distance by compared between indices of C at two sides.
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class ShortestDistanceToACharacter {
func shortestToChar(_ S: String, _ C: Character) -> [Int] {
var res = Array(repeating: 0, count: S.count), cIndex = -10000, sChars = Array(S)
for (i, sChar) in sChars.enumerated() {
if sChar == C {
cIndex = i
}
res[i] = i - cIndex
}
cIndex = -10000
for i in (0..<sChars.count).reversed() {
let currentChar = sChars[i]
if currentChar == C {
cIndex = i
}
res[i] = min(res[i], abs(cIndex - i))
}
return res
}
}