This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
preface
Js daily algorithm questions, today to a string related topic, actually feel like array processing topic, do not know whether I understand the problem, let’s have a look at the topic
Topic describes
Given a string s and an integer k, invert the first K characters of the 2k character for every 2k character count from the beginning of the string.
If there are less than k characters left, all the remaining characters are reversed.
If the remaining characters are less than 2K but greater than or equal to K, the first K characters are reversed and the remaining characters are left as is.
Example 1:
Enter: s = “abcdefg”, k = 2
Output: “bacdfeg”
Example 2:
Enter: s = “abcd”, k = 2
Output: “bacd”
Their thinking
- We’ve done a relatively simple string inversion before, and that problem inverts the entire string, and this more advanced problem inverts specific strings within a string
- The first thing I want to do is to slice it up and put it in an array so that we can do this. Since they’re saying that every 2k characters, invert the first k characters, we need to figure out how many times we need to invert the whole string
- After calculating how many reversals are required, perform each reversal through the for loop and declare two Pointers, left and right. Note that the initial positions of left and right follow the I in the for loop
- The other thing to note is that the total number of inversions required is S.length/(2 * k), remember to round up, and when the loop is finished we have the result we need by converting the array back to a string. Here’s the code
/ * * *@param {string} s
* @param {number} k
* @return {string}* /
var reverseStr = function (s, k) {
let b = s.split(' ')
let x = Math.ceil(s.length / (2 * k))// Find the total number of reversals
let left = 0
let right = k - 1
let curr = null
for (let i = 0; i < x; i++) {
curr = null
left = i * 2 * k // Reset the starting position of left and right at the beginning of each loop
right = (k - 1) + i * 2 * k
while (left < right) {
curr = b[left]
b[left] = b[right]
b[right] = curr
left++
right--
}
}
return b.join(' ') // The array is converted to a string
};
Copy the code
conclusion
This problem is also a very simple algorithm, which is the core is to turn the string array first, then a few times to see whether to reverse, the second is how each time reversal, a good location to every time to reverse the actually location of the string, the last turn after inversion array of string line, continue to refuel, gogogo