This is the fourth day of my participation in Gwen Challenge


Subject overview

Left-rotation of a string moves several characters from the beginning to the end of the string. Define a function to rotate the string left. For example, if you enter the string “abcdefg” and the number 2, the function will return “cdefgab” as a result of the left rotation.

 

Example 1:

Enter: s = “abcdefg”, k = 2

Output: “cdefgab”

Example 2:

Input: s = “lrloseumgh”, k = 6

Output: “umghlrlose”

 

Limitations:

1 <= k < s.length <= 10000

Idea 1: The lazy egg method

  • Slice — string. Slice (start, end) end means to the end when omitted

    var reverseLeftWords = function(s, n) {
         return s.slice(n) + s.slice(0, n);
    };
    Copy the code
  • Substring — string.substring(start, end) Extracts a string. End does not support negative numbers

    var reverseLeftWords = function(s, n) {
         return s.substring(n) + s.substring(n, 0);
    };
    Copy the code
  • Substr — string.substr(start, len) extracts a string of length len

    var reverseLeftWords = function(s, n) {
         return s.substr(n) + s.substr(0, n);
    };
    Copy the code

    The above three methods do not modify the array, they just extract it, or if they delete it, the splice() method.

    From a code point of view, all three approaches can be implemented and are essentially the same. So what’s the difference?

    The three methods differ only when negative numbers are passed in, and all of these methods take two arguments,

    • The Slice method adds negative numbers to the length of the string,
    • The first argument to substr is negative and adds to the length of the string, the second argument is zero,
    • Substring returns 0 whenever the argument is negative

Idea 2: Implement by interception concatenation (string with length attribute)

The purpose of this problem is to get the correct subscripts for each node. Because of the nature of increasing loops, consider a mod operation. Each of the original subscripts goes to the target subscript by 3, where does this 3 come from? It’s not hard to see that 3 is equal to len minus k. That is, for each subscript I, the target subscript is equal to I + len-k. Then simply place each element according to the new subscript.

var reverseLeftWords = function(s, n) {
    let len = s.length;
    let news = new Array(len); // A new array to return
    [...s].forEach((e,i) = >{
        news[(i + len - n) % len] = e;
    });
    return news.join("");
};
Copy the code