LeetCode's 7-day string series "344 reversed string"

LeetCode 344 reverse string

This is the first question in the string series. It is a bit simple and can be done in a few lines of code. The source of the topic is based on the website of a domestic tycoon , which is recorded here.

Title description

Write a function whose role is to reverse the input string. The input string is given in the form of a character array char[].

To allocate extra space to another array, you must modify the input array in place and use O(1) extra space to solve this problem.

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

Description: double pointer, string

Example

Input: ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a", "H"]

Problem analysis

This is a very simple question. Although the title suggests to use dual pointers to write, it can actually be written without dual pointers. It can also achieve O(1) extra space, time complexity and the use of dual pointers. the same.

That is, you can directly follow the meaning of the title and exchange the two data. In the exchange process, you can add a judgment if the elements are the same, there is no need to exchange. code show as below:

Code

lass Solution {
    
    
    public void reverseString(char[] s) {
    
    
        char temp;
        int len = s.length;
        for (int i = 0; i < len / 2; i++) {
    
    		//遍历到中间位置即可 -- 无需考虑奇偶数的情况
            if (s[i] == s[len - i - 1]) {
    
    		//相等的话就不需要交换
                continue;
            }
            temp = s[i];
            s[i] = s[len - i - 1];
            s[len - i - 1] = temp;
        }

    }
}

Program result

Program execution result

Guess you like

Origin blog.csdn.net/weixin_44184990/article/details/108612699