代码随想录Day8 - 344.反转字符串 |541. 反转字符串II | 151.翻转字符串里的单词 |3110. 字符串的分数

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值