假设我们有一个字符数组。我们必须反转字符串而不使用任何额外的空间。因此,如果字符串类似于['H','E','L','L','O'],则输出将为['O','L','L','E',' H']
为了解决这个问题,我们将遵循以下步骤-
用两个指针开始= 0,结束=字符串的长度– 1
交换第一个和最后一个字符
开始增加1,结束减少1
让我们看下面的实现以更好地理解-
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ start = 0 end = len(s)-1 while start<end: s[start],s[end] = s[end],s[start] start+=1 end-=1string_1 = ["H","E","L","L","O"] ob1 = Solution()ob1.reverseString(string_1) print(string_1)
String = ["H","E","L","L","O"]
输出结果
["O","L","L","E","H"]