LeetCode: 344. Reverse String-简单-Python+Java

LeetCode: 344. Reverse String-简单-Python+Java,第1张

概述344. Reverse String 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 th 344. Reverse String 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","o"] Output: ["o","h"] Example 2: input: ["H","a","n","h"] Output: ["h","H"]   解题思路: 用两个指针,分别指向头和尾,互相交换值(java需要一个temp变量来保存值 O(1)),头指针向后移动,尾指针向前移动,直到头指针大于等于尾部指针 时间 o(n/2) 空间o(1)   Java:
class Solution {    public voID reverseString(char[] s) {        int start = 0;        int end = s.length-1;        while(start<end){            char tmp = s[end];            s[end--] = s[start];            s[start++] = tmp;        }    }}

 Python:

class Solution(object):    def reverseString(self,s):        """        :type s: List[str]        :rtype: None Do not return anything,modify s in-place instead.        """        start,end = 0,len(s)-1        while start < end:            s[start],s[end] = s[end],s[start];            start += 1            end -= 1
总结

以上是内存溢出为你收集整理的LeetCode: 344. Reverse String-简单-Python+Java全部内容,希望文章能够帮你解决LeetCode: 344. Reverse String-简单-Python+Java所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1191351.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存