Topic describes

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.

Topic Example 1

Enter: s ="abcdefg", k = 2Output:"cdefgab"
Copy the code

Topic Example 2

Enter: s ="lrloseumgh", k = 6Output:"umghlrlose"
Copy the code

Subject analysis

The problem is relatively simple, using JS native API can be solved, can also use regular expressions

Code implementation

/ * * *@param {string} s
 * @param {number} n
 * @return {string}* /
var reverseLeftWords = function(s, n) {
    // Method one uses either substring or slice
    return s.substring(n, s.length) + s.substring(0, n)
    
    // Use regular expressions
    return s.replace(new RegExp(`([a-z]{${n}})([a-z]{${s.length - n}}) `), '$2 $1')
    // It is also possible to divide a string into an array and then regroup it
};
Copy the code

Title source

LeetCode: Reference to Offer 58-II. Left-rotate string