“This is the seventh day of my participation in the First Challenge 2022.
preface
Today’s topic is simple, found the Spring Festival this period is simple, may be the official to let everyone have a good year.
A daily topic
Today’s daily lesson is 2000. Reverse word prefixes. The difficulty is simple
-
You are given a string word with subscripts starting at 0 and a character ch. Find the subscript I of the first occurrence of ch and invert the character in Word from subscript 0 to subscript I, including subscript I. If the character CH does not exist in Word, no operation is required.
-
For example, if word = “abcdefd” and ch = “d”, then you should reverse from subscript 0 to subscript 3 (including 3). The resulting string will be “dcbaefd”.
-
Returns the result string.
Example 1:
Enter: word ="abcdefd", ch = "d"Output:"dcbaefd"Explanation:"d"It first appears in the subscript3. Invert from the subscript0The subscript3(subscript3), the resulting string is"dcbaefd" 。
Copy the code
Example 2:
Enter: word ="xyxzxe", ch = "z"Output:"zxyxxe"Explanation:"z"The first and only time it happens is in the subscript3. Invert from the subscript0The subscript3(subscript3), the resulting string is"zxyxxe" 。
Copy the code
Example 3:
Enter: word ="abcd", ch = "z"Output:"abcd"Explanation:"z"Does not exist in Word. There is no need to perform an inversion operation, the resulting string is"abcd" 。
Copy the code
Tip:
- 1 <= word.length <= 250
- Word consists of lowercase English letters
- Ch is a lowercase letter
Answer key
Violent solution
First, we can use the string indexOf method to find the position of the character CH in Word, and use a variable index to store the position of the character CH. If it is -1, it does not exist and does not need to operate, so we can return word directly. If it exists, we can continue to operate on the string. So, the string that needs to be reversed is 0-index, and then the string that needs to be reversed is returned.
Cycle reversal
Then invert the string part, we can get the beginning and end of the part that we want to invert from 0-index, we can use a loop, just loop index/2 times, and then invert the two symmetric characters each time and return the whole reversed string.
/ * * *@param {string} word
* @param {character} ch
* @return {string}* /
var reversePrefix = function (word, ch) {
const index = word.indexOf(ch);
if (index >= 0) {
const arr = [...word];
let left = 0, right = F;
for (let i = 0; i < index / 2; i++) {
const temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
word = arr.join(' ');
}
return word;
};
Copy the code
Double pointer reversal
Left ++, right–, end the loop only if left>right. Then the reverse part above can also be written as:
if (index >= 0) {
const arr = [...word];
let left = 0, right = index;
while (left < right) {
const temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
word = arr.join(' ');
}
Copy the code