Python 反转字符串
假设我们有一个字符数组。我们必须在不使用任何其他空间的情况下反转字符串。所以如果字符串像 [‘H’, ‘E’, ‘L’, ‘L’, ‘O’],输出将是 [‘O’, ‘L’, ‘L’, ‘E’, ‘H’]
要解决这个问题,我们将遵循以下步骤:
- 取两个指针,start = 0 和 end = 字符串的长度 – 1
- 交换第一个和最后一个字符
- start 增加 1,end 减少 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"]
广告