-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-collisions-on-a-road.go
54 lines (53 loc) · 1.13 KB
/
count-collisions-on-a-road.go
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
package leetcode_solutions_golang
//https://leetcode.com/problems/count-collisions-on-a-road/
func countCollisions(directions string) int {
arr := []rune(directions)
total := 0
size := len(arr)
for i := 0; i < size; i++ {
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'L' {
arr[i] = 'S'
arr[i+1] = 'S'
total += 2
}
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'S' {
arr[i] = 'S'
total++
}
if i > 0 && arr[i] == 'L' && arr[i-1] == 'S' {
arr[i] = 'S'
total++
}
}
for i := 0; i < size; i++ {
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'L' {
arr[i] = 'S'
arr[i+1] = 'S'
total += 2
}
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'S' {
arr[i] = 'S'
total++
}
if i > 0 && arr[i] == 'L' && arr[i-1] == 'S' {
arr[i] = 'S'
total++
}
}
for i := size - 1; i >= 0; i-- {
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'L' {
arr[i] = 'S'
arr[i+1] = 'S'
total += 2
}
if i < len(arr)-1 && arr[i] == 'R' && arr[i+1] == 'S' {
arr[i] = 'S'
total++
}
if i > 0 && arr[i] == 'L' && arr[i-1] == 'S' {
arr[i] = 'S'
total++
}
}
return total
}