LeetCode 344. Reverse String

Description

Write a function that reverses a string. The input string is given as an array of characters char[].git

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.github

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:ui

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]this

描述

編寫一個函數,其做用是將輸入的字符串反轉過來。輸入字符串以字符數組 char[] 的形式給出。spa

不要給另外的數組分配額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。code

你能夠假設數組中的全部字符都是 ASCII 碼錶中的可打印字符。索引

示例 1:ip

輸入:["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]

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.

相關文章
相關標籤/搜索