LeetCode 344. Reverse String
Description
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
描述
編寫一個函式,其作用是將輸入的字串反轉過來。輸入字串以字元陣列 char[] 的形式給出。
不要給另外的陣列分配額外的空間,你必須原地修改輸入陣列、使用 O(1) 的額外空間解決這一問題。
你可以假設陣列中的所有字元都是 ASCII 碼錶中的可列印字元。
示例 1:
輸入:["h","e","l","l","o"]
輸出:["o","l","l","e","h"]
示例 2:
輸入:["H","a","n","n","a","h"]
輸出:["h","a","n","n","a","H"]
思路
- 第一個位置的元素和嘴後一個位置的元素交換,第二個和倒數第二個,第三個和倒數第三個 ...
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-04-08 21:47:07 # @Last Modified by:何睿 # @Last Modified time: 2019-04-08 21:54:18 class Solution: def reverseString(self, s: [str]) -> None: """ Do not return anything, modify s in-place instead. """ # 中間位置的索引,最後一個位置的索引 half, count = len(s) // 2, len(s) - 1 for i in range(half): s[i], s[count - i] = s[count - i], s[i]
原始碼檔案在這裡 。
©本文首發於 何睿的部落格 ,歡迎轉載,轉載需保留文章來源 ,作者資訊和本宣告.