2
头图

Reverse string

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[].

Don't allocate extra space for 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.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: array traversal
Traversal s, traversal order is 0~s.length/2 , the first i value of the item and s.length-1-i value of the item exchange. The s after the traversal is completed is the reversed string.
public class LeetCode_344 {
    public static void reverseString(char[] s) {
        for (int i = 0; i < s.length / 2; i++) {
            // 第i项和第s.length-1-i项进行交换
            char temp = s[i];
            s[i] = s[s.length - 1 - i];
            s[s.length - 1 - i] = temp;
        }
    }

    public static void main(String[] args) {
        char[] s = new char[]{'h', 'e', 'l', 'l', 'o'};
        System.out.println("-----反转之前-----");
        for (char c : s) {
            System.out.print(c + " ");
        }
        System.out.println();
        reverseString(s);
        System.out.println("-----反转之后-----");
        for (char c : s) {
            System.out.print(c + " ");
        }
    }
}
[Daily Message] Every breakthrough is to achieve a better self.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!