LeetCode: 344. Reverse String-简单-Python+Java
发布时间:2020-12-20 10:42:44 所属栏目:Python 来源:网络整理
导读: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
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |