LeetCode - 344. Reverse String

topic

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"]

Problem-solving ideas

This is a classic inverting title string, difficulty is not required to apply for additional memory space, and requires the time complexity is O (1). The first contact with this type of student will probably ignorant force, in fact, this question can be converted into other questions:

How to exchange value of the two numbers x, y in the case do not take up any extra space?

Herein may be utilized to solve the XOR operation, XOR following properties:

  1. The same number of two exclusive OR result is 0
  2. Any number of 0 or XOR result of its own
  3. Exclusive-OR operation is commutative and associative

Thus there is such an idea: the first and last characters of the string by an exclusive OR operation to exchange positions with each other, such as the first and last character position interchanged, second and second last swap positions, a total cycle number string length / 2, so that the desired effect can be achieved subject. code show as below:

class Solution {
    public void reverseString(char[] s) {
        int size = s.length;
        int a = size / 2;
        int last;
        for (int i = 0; i < a; i++) {
            last = size - 1 - i;
            s[i] ^= s[last];
            s[last] ^= s[i];
            s[i] ^= s[last];
        }
    }
}

Below is the time and memory consumption:

Runtime: 1 ms
Memory Usage: 51.6 MB

Related Links

Guess you like

Origin www.cnblogs.com/yulinlewis/p/10990738.html