This is the fifth day of my participation in the August Wen Challenge.More challenges in August

Inverted string

The title

Write a function that reverses the input string. The input string is given in the form of the character array char[].

Instead of allocating extra space to another array, you must modify the input array in place, using O(1) extra space to solve the problem.

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

 

Example 1: input: [" h ", "e", "l", "l", "o"] output: [" o ", "l", "l", "e", "h"]Copy the code

Answer key

Idea 1: Find the middle point, set the left and right sides of the middle point as the left and right Pointers, and spread to both sides for exchange. The intermediate point is determined by the parity of the array length. Even numbers, the left and right Pointers point to the first and second half of the length; Odd, the left and right Pointers point to the left and right of the middle number.

Idea 2:

Set left and right Pointers to head and tail respectively. When the left and right Pointers meet, or when the left exceeds the right, they break out of the loop and return the array.

code

Idea 1:

var reverseString = function (s) {
    let l, r
    if (s.length % 2= = =0) {
        l = (s.length >> 1) - 1
        r = s.length >> 1
    } else {
        l = (s.length >> 1) - 1
        r = (s.length >> 1) + 1
    }
    while (l >= 0 && r < s.length) {
        swap(s, l--, r++)
    }
    return s
};
function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
Copy the code

Idea 2:

var reverseString = function (s) {
    let l = 0, r = s.length - 1
    while (l < r) {
        swap(s, l++, r--)
    }
    return s
};
function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
Copy the code

Invert the word III in the string

The title

Given a string, you need to reverse the character order of each word in the string, while still preserving the Spaces and the original order of the words.

Example: Enter: "Let's take LeetCode contest" Output: "s 'tel ekat edoCteeL tsetnoc"Copy the code

Answer key

This problem focuses on switching between strings and arrays, as well as array inversion. The string is first divided into arrays by Spaces, and then in each small string segment, it is reversed into arrays, and then the string is assembled. Finally, concatenate it with Spaces into a long string.

code

var reverseWords = function (s) {
    let arr = s.split(' ')
    let res = []
    for (let i = 0; i < arr.length; i++) {
        res.push(arr[i].split(' ').reverse().join(' '))}return res.join(' ')};Copy the code

LeetCode