Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit dae3f9c

Browse files
committed
899 finish
1 parent 1a8c871 commit dae3f9c

File tree

2 files changed

+37
-20
lines changed

2 files changed

+37
-20
lines changed
Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,42 @@
11
package problem0899
22

3-
func orderlyQueue(s string, k int) string {
4-
seen := make(map[string]bool, len(s))
5-
min := s
6-
helper(s, k, &min, seen)
7-
return min
8-
}
9-
10-
func helper(s string, k int, min *string, seen map[string]bool) {
11-
if seen[s] {
12-
return
13-
}
3+
import (
4+
"sort"
5+
)
146

15-
seen[s] = true
16-
if *min > s {
17-
*min = s
7+
func orderlyQueue(s string, k int) string {
8+
if k == 1 {
9+
return minRotated(s)
1810
}
11+
// 当 k >=2 时
12+
// 前两个位置上的字母,总是把较小的字母移到末尾
13+
// 经过 len(s)-1 次比较后,s 中最大的字母,一定在前两个位置中,
14+
// 此时,把 s 中最大的字母移到末尾。
15+
// 以此类推,可以形成一个冒泡排序。
16+
// 所以,当 k >= 2 时,可以直接对 s 进行排序
17+
// 当 k = 1 时,无法进行比较
18+
// 就只能通过回转 s 来查看最小的字符串了
19+
return sorted(s)
20+
}
1921

20-
for i := 0; i < k; i++ {
21-
helper(move(s, i), k, min, seen)
22+
func minRotated(s string) string {
23+
min := s
24+
bytes := []byte(s)
25+
bytes = append(bytes, bytes...)
26+
size := len(s)
27+
for i := 1; i < size; i++ {
28+
rs := string(bytes[i : i+size])
29+
if min > rs {
30+
min = rs
31+
}
2232
}
33+
return min
2334
}
2435

25-
func move(s string, i int) string {
36+
func sorted(s string) string {
2637
bytes := []byte(s)
27-
b := bytes[i]
28-
copy(bytes[i:], bytes[i+1:])
29-
bytes[len(bytes)-1] = b
38+
sort.Slice(bytes, func(i int, j int) bool {
39+
return bytes[i] < bytes[j]
40+
})
3041
return string(bytes)
3142
}

Algorithms/0899.orderly-queue/orderly-queue_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ var tcs = []struct {
2626
"abcde",
2727
},
2828

29+
{
30+
"dasfkasdlkfasdlkjflaksdjflksdajflkasdjflksdajflkasdjflkasdj",
31+
3,
32+
"aaaaaaaaadddddddddffffffffjjjjjjjkkkkkkkkkllllllllsssssssss",
33+
},
34+
2935
{
3036
"baaca",
3137
3,

0 commit comments

Comments
 (0)