LeetCode 541. 反转字符串II

题目

给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。如果剩余字符少于 k 个,则将剩余字符全部反转。如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
例:
输入:s = "abcdefg", k = 2
输出:"bacdfeg"

方法

遍历字符串,设置步长为 2k,每次对需要进行反转的区间进行翻转

class Solution(object):
    def reverseStr(self, s, k):
        def reverse(text):
            left, right = 0, len(text)-1
            while left < right:
                text[left], text[right] = text[right], text[left]
                left += 1
                right -= 1
            return text

        result = list(s)

        for i in range(0, len(s), 2 * k):
            result[i: i + k] = reverse(result[i: i + k])

        return ''.join(result)
相关知识
  • 边界处理:
    字符串或列表的末尾如果超过最大长度,则会返回至其最后一个值。
    字符串:若存在字符串 a = "abcdefg",那么 a[0:999] 的返回值为 'abcdefg'
    列表:若存在列表 b = list(a),那么 b[0:999] 的返回值为 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  • 列表转换为字符串:
    使用 join 函数:''.join()
报错
  • ‘unicode’ object does not support item assigment

    因为字符串是不可变的,所以无法直接改变字符串的值,所以需要将其转换为列表
参考

代码相关:https://programmercarl.com/0541.%E5%8F%8D%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2II.html
列表转换为字符串:https://blog.csdn.net/cunjiu9486/article/details/109074785

你可能感兴趣的:(LeetCode 541. 反转字符串II)