题目
代码
执行用时:36 ms, 在所有 Python3 提交中击败了61.20% 的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了78.80% 的用户
通过测试用例:34 / 34
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:]+s[:n]
【方法2】
执行用时:36 ms, 在所有 Python3 提交中击败了61.20% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了38.62% 的用户
通过测试用例:34 / 34
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
ans=[' ']*len(s)
for i in range(len(s)):
if i>=n:
ans[i-n]=s[i]
else:
ans[len(s)-n+i]=s[i]
return "".join(ans)
【方法3】
执行用时:36 ms, 在所有 Python3 提交中击败了61.20% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了37.15% 的用户
通过测试用例:34 / 34
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
ans=[]
for i in range(n,n+len(s)):
ans.append(s[i%len(s)])
return "".join(ans)

该博客讨论了三种不同的Python实现方式,用于反转字符串的前n个字符。所有方法在执行时间和内存消耗上表现相当,都在36毫秒内完成,并在不同测试用例中通过了34/34的检查。这些方法展示了如何利用切片和循环来有效地操作字符串。
237

被折叠的 条评论
为什么被折叠?



