Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 149dc3d

Browse files
author
侯利朋
committed
.\821.shortest-distance-to-a-character ok
1 parent 37865a0 commit 149dc3d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* @lc app=leetcode id=821 lang=golang
3+
*
4+
* [821] Shortest Distance to a Character
5+
*/
6+
// 0 ms
7+
// 遍历两遍
8+
func shortestToChar(S string, C byte) []int {
9+
10+
rtn := make([]int, len(S))
11+
12+
// 左往右
13+
pri := -len(S) // 前一个C的位置, 初始为-len(S), 则rtn中记录的值肯定比右往左的时候大
14+
for i := 0; i < len(S); i++ {
15+
if S[i] == C {
16+
pri = i
17+
}
18+
rtn[i] = i - pri
19+
}
20+
21+
// 右往左
22+
next := len(S) * 2 // 2倍长度,保证右往左的时候最大
23+
for i := len(S) - 1; i >= 0; i-- {
24+
if S[i] == C {
25+
next = i
26+
}
27+
if rtn[i] > next-i {
28+
rtn[i] = next - i
29+
}
30+
}
31+
return rtn
32+
}

0 commit comments

Comments
 (0)