反转字符串
https://leetcode.cn/problems/reverse-string/
思路
使用双指针,初始化时,left指向下标0的位置,right指向最后一个元素的下标 当while left<right时,交换nums[left]和nums[right],直到结束整个循环
class Solution : def reverseString ( self, s: List[ str ] ) - > None : """Do not return anything, modify s in-place instead.""" left, right = 0 , len ( s) - 1 while left< right: s[ left] , s[ right] = s[ right] , s[ left] left+= 1 right-= 1
反转字符串II
https://leetcode.cn/problems/reverse-string-ii/description/
思路
先定义一个反转字符串的函数reverse,并传入一个参数,返回一个已经反转了的字符串 再以2k为步长遍历整个字符串,每遍历一次将前k个字符串nums[cur:cur+k]传递给上面的函数,接受返回的字符串res=reverse(text),并修改原来的nums[cur:cur+k]=res
class Solution : def reverseStr ( self, s: str , k: int ) - > str : 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 textarr = list ( s) for cur in range ( 0 , len ( s) , 2 * k) : res = reverse( arr[ cur: cur+ k] ) arr[ cur: cur+ k] = resreturn "" . join( arr)
class Solution : def reverse ( self, text) : left, right = 0 , len ( text) - 1 while left< right: text[ left] , text[ right] = text[ right] , text[ left] left+= 1 right-= 1 return textdef reverseStr ( self, s: str , k: int ) - > str : arr = list ( s) for cur in range ( 0 , len ( s) , 2 * k) : res = self. reverse( arr[ cur: cur+ k] ) arr[ cur: cur+ k] = resreturn "" . join( arr)
替换数字
https://kamacoder.com/problempage.php?pid=1064
思路
将s转化为列表lst,遍历列表lst,如果lst[i]为整数,则lst[i] = 'number',否则i++ 遍历完之后,将列表lst转化为字符串(使用''.join(lst))
class Solution : def __init__ ( self) : self. t = 'number' self. tmp = [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ] def replace ( self) : s = input ( ) lst = list ( s) for i in range ( len ( s) ) : if lst[ i] in self. tmp: lst[ i] = self. tprint ( '' . join( lst) ) obj = Solution( )
obj. replace( )