美文网首页
344. Reverse String

344. Reverse String

作者: 随时学丫 | 来源:发表于2020-01-05 13:55 被阅读0次

344. Reverse String

Easy

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"]

数组翻转

只需要将数组前一半和后面一半进行交换即可

Java

class Solution {
    public void reverseString(char[] s) {
        if(s == null || s.length == 0) return;
        int len = s.length/2;
        for(int i=0; i<len; i++){
            char temp = s[s.length-1-i];
            s[s.length-1-i] = s[i];
            s[i] = temp;
        }
    }
}

Python

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        len_ = len(s)//2
        for i in range(len_):
            s[len(s)-1-i], s[i] = s[i], s[len(s)-1-i]
        return s

相关文章

  • 2019-04-08

    LeetCode 344. Reverse String Description Write a function...

  • 344. Reverse String

    344. Reverse String Easy Write a function that reverses a...

  • 344. 反转字符串

    344. 反转字符串[https://leetcode.cn/problems/reverse-string/] ...

  • 344. Reverse String

    344. Reverse String Python: 最Pythonic的解法咯 Discuss有人问如下解法为...

  • String

    唐博主刷了String,我那周太忙了,需要慢慢自己补啦。344. Reverse String : Easy3....

  • 344. Reverse String

    https://leetcode.com/problems/reverse-string/description/...

  • 344. Reverse String

    Leetcode Day 1 344 Reverse String 题目:Write a function tha...

  • 344. Reverse String

    Problem Write a function that takes a string as input and...

  • 344. Reverse String

    Write a function that takes a string as input and returns...

  • 344. Reverse String

    1.描述 Write a function that takes a string as input and re...

网友评论

      本文标题:344. Reverse String

      本文链接:https://www.haomeiwen.com/subject/wjnqactx.html