Skip to content

Commit bcf217f

Browse files
committed
Update solution 1663
1 parent 096da77 commit bcf217f

File tree

3 files changed

+31
-37
lines changed

3 files changed

+31
-37
lines changed

leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/1663. Smallest String With A Given Numeric Value.go

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,17 @@ package leetcode
22

33
// 解法一 贪心
44
func getSmallestString(n int, k int) string {
5-
res := make([]rune, n)
6-
for i := n - 1; i >= 0; i-- {
7-
diff := k - i
8-
if diff >= 26 {
9-
// Need to add z
10-
res[i] = 'z'
11-
k = k - 26
12-
} else {
13-
res[i] = rune('a' + diff - 1)
14-
k = k - diff
5+
str, i, j := make([]byte, n), 0, 0
6+
for i = n - 1; i <= k-26; i, k = i-1, k-26 {
7+
str[i] = 'z'
8+
}
9+
if i >= 0 {
10+
str[i] = byte('a' + k - 1 - i)
11+
for ; j < i; j++ {
12+
str[j] = 'a'
1513
}
1614
}
17-
return string(res)
15+
return string(str)
1816
}
1917

2018
// 解法二 DFS

leetcode/1663.Smallest-String-With-A-Given-Numeric-Value/README.md

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,17 @@ package leetcode
5050

5151
// 解法一 贪心
5252
func getSmallestString(n int, k int) string {
53-
res := make([]rune, n)
54-
for i := n - 1; i >= 0; i-- {
55-
diff := k - i
56-
if diff >= 26 {
57-
// Need to add z
58-
res[i] = 'z'
59-
k = k - 26
60-
} else {
61-
res[i] = rune('a' + diff - 1)
62-
k = k - diff
63-
}
64-
}
65-
return string(res)
53+
str, i, j := make([]byte, n), 0, 0
54+
for i = n-1; i <= k-26; i, k = i-1, k-26 {
55+
str[i] = 'z'
56+
}
57+
if i >= 0 {
58+
str[i] = byte('a' + k-1-i)
59+
for ; j < i; j++ {
60+
str[j] = 'a'
61+
}
62+
}
63+
return string(str)
6664
}
6765

6866
// 解法二 DFS

website/content/ChapterFour/1663.Smallest-String-With-A-Given-Numeric-Value.md

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,17 @@ package leetcode
5050

5151
// 解法一 贪心
5252
func getSmallestString(n int, k int) string {
53-
res := make([]rune, n)
54-
for i := n - 1; i >= 0; i-- {
55-
diff := k - i
56-
if diff >= 26 {
57-
// Need to add z
58-
res[i] = 'z'
59-
k = k - 26
60-
} else {
61-
res[i] = rune('a' + diff - 1)
62-
k = k - diff
63-
}
64-
}
65-
return string(res)
53+
str, i, j := make([]byte, n), 0, 0
54+
for i = n-1; i <= k-26; i, k = i-1, k-26 {
55+
str[i] = 'z'
56+
}
57+
if i >= 0 {
58+
str[i] = byte('a' + k-1-i)
59+
for ; j < i; j++ {
60+
str[j] = 'a'
61+
}
62+
}
63+
return string(str)
6664
}
6765

6866
// 解法二 DFS

0 commit comments

Comments
 (0)