好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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","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需要一个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的详细内容...

  阅读:18次