344.反转字符串: Reverse String
思路: 用双指针, 没啥好说的,秒
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# 用双指针 l = 0, r = len(nums) - 1, 然后nums[l] = nums[r], l和r向中间移动直到l = r停止
# 注意:array中才能用s[l] = s[r], string中不能用这个, 会显示“'str' object does not support item assignment”
l = 0
r = len(s) - 1
while (l < r):
s[l],s[r] = s[r], s[l]
# temp = s[l]
# s[l] = s[r]
# s[r] = temp
l += 1
r -= 1
return s
541. 反转字符串II :Reverse String II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
ret = ""
turn = 0
# turn: 0 1 2 3
# 创建subarray: ab, cd, ef,g
# 定义一个turn 从0开始往后加1, 如果turn为偶数就反转,为奇数就不反转, 反转快捷操作a[::-1]
for i in range(0, len(s),k):
sub = s[i:i+k]
if (turn % 2 == 0):
sub = sub[::-1] # string中不能用s[l] = s[r] ,会显示bug “'str' object does not support item assignment”
ret += sub
turn += 1
return ret
151.翻转字符串里的单词: Reverse Words in a String
class Solution:
def reverseWords(self, s: str) -> str:
# 将string 拆分成 list of string, 用split()函数
words = s.split() # split出来的是list of string: ['the', 'sky', 'is', 'blue']
print(words)
print(type(words))
# 然后和 344.reverse string那一题一样, 左右指针,直接交换
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
# 将列表转换成字符串
return " ".join(words) #将array加到string中
3110. 字符串的分数 3110. Score of a String
class Solution:
def scoreOfString(self, s: str) -> int:
# 将character变成ASCII value, 用ord(字母) 函数
ret = 0
for i in range(len(s) - 1):
rel_dif = abs(ord(s[i]) - ord(s[i+1]))
ret += rel_dif
# print(ret)
return ret