Created
December 27, 2018 12:32
-
-
Save Sherlock-Holo/79d4a2b1d20f91c2787c10479f0d7a30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"testing" | |
) | |
const S = "abcdddeeeeaabbbcd" | |
func largeGroupPositions(S string) (res [][]int) { | |
tmpSlice := make([]int, 2) | |
var ( | |
tmpRune rune | |
count int | |
) | |
for i, r := range []rune(S) { | |
if i == 0 { | |
tmpSlice[0], tmpSlice[1] = i, i | |
count++ | |
tmpRune = r | |
continue | |
} | |
if r == tmpRune { | |
tmpSlice[1] = i | |
count++ | |
continue | |
} | |
if count >= 3 { | |
res = append(res, tmpSlice) | |
tmpSlice = []int{i, i} | |
count = 1 | |
tmpRune = r | |
continue | |
} | |
tmpSlice[0], tmpSlice[1] = i, i | |
count = 1 | |
tmpRune = r | |
} | |
if count >= 3 { | |
res = append(res, tmpSlice) | |
} | |
return | |
} | |
func largeGroupPositions2(S string) [][]int { | |
r := [][]int{} | |
n := len(S) | |
if n < 3 { | |
return r | |
} | |
for i := 0; i < n; i++ { | |
tmpStart := i | |
for i < n-1 && S[i] == S[i+1] { | |
i++ | |
} | |
tmpEnd := i | |
if tmpEnd-tmpStart >= 2 { | |
r = append(r, []int{tmpStart, tmpEnd}) | |
} | |
} | |
return r | |
} | |
func largeGroupPositions3(S string) (res [][]int) { | |
// tmpSlice := make([]int, 2) | |
var ( | |
tmpStart int | |
tmpEnd int | |
tmpRune rune | |
count int | |
) | |
for i, r := range []rune(S) { | |
if i == 0 { | |
// tmpSlice[0], tmpSlice[1] = i, i | |
tmpStart, tmpEnd = i, i | |
count++ | |
tmpRune = r | |
continue | |
} | |
if r == tmpRune { | |
// tmpSlice[1] = i | |
tmpEnd = i | |
count++ | |
continue | |
} | |
if count >= 3 { | |
res = append(res, []int{tmpStart, tmpEnd}) | |
// tmpSlice = []int{i, i} | |
count = 1 | |
tmpRune = r | |
continue | |
} | |
// tmpSlice[0], tmpSlice[1] = i, i | |
tmpStart, tmpEnd = i, i | |
count = 1 | |
tmpRune = r | |
} | |
if count >= 3 { | |
res = append(res, []int{tmpStart, tmpEnd}) | |
} | |
return | |
} | |
func Benchmark1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = largeGroupPositions(S) | |
} | |
} | |
func Benchmark2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = largeGroupPositions2(S) | |
} | |
} | |
func Benchmark3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = largeGroupPositions3(S) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment