Leetcode 344:Reverse String 反转字符串(python、java)

栏目: Python · 发布时间: 6年前

内容简介:公众号:爱写bugWrite a function that reverses a string. The input string is given as an array of charactersDo not allocate extra space for another array, you must do this by

Leetcode 344:Reverse String 反转字符串

公众号:爱写bug

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

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须 原地修改输入数组 、使用 O(1) 的额外空间解决这一问题。

你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

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) {
        char temp;
        for(int i=0,j=s.length-1;i<j;i++,j--){
            temp=s[i];
            s[i]=s[j];
            s[j]=temp;
        }
    }
}

Python3:

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        i = 0
        j = len(s) - 1
        while (i < j):
            s[i], s[j] = s[j], s[i]#交换赋值
            i+=1
            j-=1

其实py3有很多好玩的操作,比如这道题可以这样: s=list(reversed(s)) 因为 reversed() 函数返回的是一个迭代器,所以要用 list() 函数才行。但是速度不快。

如果是字符串反转而不是数组还可以这样 s=s[::-1] (字符串切片: string[start:stop:step]

总结:

这道题应当解释双指针问题最常引用的题目了,其思想是将第一个元素与末尾进行交换,再向前移动到下一个元素,并不断地交换,直到它到达中间位置。

我们可以同时使用两个指针来完成迭代:一个 从第一个元素开始 ,另一个 从最后一个元素开始 。持续交换它们所指向的元素,直到这两个指针相遇。

摘自Leetcode:

总之,使用双指针技巧的典型场景之一是你想要

从两端向中间迭代数组。

这时你可以使用双指针技巧:

一个指针从始端开始,而另一个指针从末端开始。

Leetcode 344:Reverse String 反转字符串(python、java)


以上所述就是小编给大家介绍的《Leetcode 344:Reverse String 反转字符串(python、java)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithm Design

Algorithm Design

Jon Kleinberg、Éva Tardos / Addison-Wesley / 2005-3-26 / USD 144.20

Algorithm Design introduces algorithms by looking at the real-world problems that motivate them. The book teaches students a range of design and analysis techniques for problems that arise in compu......一起来看看 《Algorithm Design》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具