leetcode: Reverse a string

topic

Write a function, its role is to input string reversed. Input string to a character array char[]given form.

Do not allocate additional space to another array, you must place modify the input array , using the extra space O (1) solution to this problem.

You may assume that all the characters in the array are the ASCII code table printable characters.

Example 1:

输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]

Example 2:

输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

Thinking

This question is returned in the previous array of characters, but now replaced by in situ modification, no return value. This makes the use of high-level functions have been locked out, if you can return an array of characters, so Python can be directly used in return s[::-1]this article statements to be reversed, in high-level languages such as Java have reverse()such a function.

Now then change the title, the idea is limited, you need to use two pointers for data exchange. Traverse half of the array, the two numbers can be sequentially exchanged.

Unfortunately, LeetCode value has not been allowed to return to answer this question before the answer give up on the ranking, I can not judge whether this the best solution, if any better solution, welcome message informed.

As shown below, the top-ranking answer does not comply with current topics

Schematically

achieve

Although I already try to optimize statement, such as use in Python s[i], s[j] = s[j], s[i]data exchange instead of by means of an intermediate variable exchange to save time, but still consumes 196 ms of time, but in fact the algorithm time complexity is only O (n /2)

C language

void reverseString(char* s, int sSize) {
    int temp;
    for(int i=0; i<sSize/2; i++){
        temp = s[i];
        s[i] = s[sSize-i-1];
        s[sSize-i-1] = temp;
    }
}

Python

class Solution:
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: void Do not return anything, modify s in-place instead.
        """
        j = len(s)-1
        for i in range(int(len(s)/2)):
            s[i], s[j] = s[j], s[i]
            j -= 1
            i += 1


Reprinted link: https: //www.jianshu.com/p/e982ea5bdaa0

Guess you like

Origin blog.csdn.net/dq932073495/article/details/92402745