avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

1663. The smallest string with a given value One question daily

  2024-01-01        
字数统计: 315字   |   阅读时长: 1min

2023-01-26.png
1663. The smallest string with a given value

Thought:

今天的One question daily读题可以得知:Actually I want to ask for:
27 How to disassemble 3 Number 1 + 1 + 25
73 How to disassemble 5 Number 1 + 1 + 19 + 26 + 26
nIs the number of string we are going to return,So we put itaAs1,Createnindivual1list of[1]*n
贪心Thought
First time:从第一Number开始加,Add to26。Determine whether it is with each timekequal,Timeout。
Second attempt:Turn all the numbers passed directly into26,Turn all the numbers passed directly into26,kEvery time-25,最后将Remaining数字Add to我们遍历到的位置
,Last+Remainingk。
The optimal solution is not usedlambdaThe function converts the number into a string,Instead‘a’Become up to become‘z’。Save a lot of time。

Code:

[]First time(time out)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
def find(list_ans):
for i in range(n):
while list_ans[i] < 26:
if sum(list_ans) == k:
return list_ans
list_ans[i] += 1
return list_ans

list1 = [1] * n
list1 = ''.join(list(map(lambda x: chr(x), map(lambda x: x + 96, find(list1)))))[::-1]
return list1
[]Second attempt(500ms)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
index = n - 1
list1 = [1] * n
k -= n
while k > 25:
list1[index] += 25
k -= 25
index -= 1
# How much is left?
print(k)
list1[index] += k
return ''.join(list(map(lambda x: chr(x), map(lambda x: x + 96, list1))))
[]Optimal solution(100ms)
1
2
3
4
5
6
7
8
9
10
class Solution:
def getSmallestString(self, n: int, k: int) -> str:
ans = ['a'] * n
i, d = n - 1, k - n
while d > 25:
ans[i] = 'z'
d -= 25
i -= 1
ans[i] = chr(ord(ans[i]) + d)
return ''.join(ans)
  • Python
  • answer
  • One question daily

扫一扫,分享到微信

微信分享二维码
1590.Make the array and energyPDivide
1664. Number of schemes to generate balance numbers One question daily
目录
  1. 1. Thought:
  2. 2. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号