代码训练营 Day8 | 344.反转字符串 | 541.反转字符串II |

344.反转字符串

  1. 使用双指针一个指针指向数组开始的位置,一个指针指向数组结束的位置
  2. 通过循环让两个指针元素相互交换知道两个指针碰到一起
class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        # use two pointer
        left = 0
        right = len(s) - 1
        temp = 0

        # iterate the list
        while right >= left:
            # swap the element
            temp = s[right]
            s[right] = s[left]
            s[left] = temp

            right -= 1
            left += 1
        
        # return original array
        return s

541.反转字符串II 

  1. 判断 i+k <= s.size 才进行反转,保证i+k要在数组范围内

  2. 反转跟344题逻辑一样写一个函数调用即可

class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        
        def subString(text):
            # reverse the letter
            left = 0
            right = len(text)-1

            while right >= left:
                # sawp 
                text[left],text[right] = text[right],text[left]
                
                right -= 1
                left += 1

            return text
        
        # convert the string to list,easy to operate
        result = list(s)

        for cur in range(0,len(s),2*k):
            result[cur:cur+k] = subString(result[cur:cur+k])
        
        return "".join(result)

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值