反轉字符串
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( )