“This is the 15th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Day 37 2021.02.02

2000. Reverse word prefixes

  • Leetcode: leetcode-cn.com/problems/re…
  • Difficulty: Easy
  • Method: Flip the string method

The title

  • 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.

The sample

  • Example 1
Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation: "d" first appears at subscript 3. Invert the character from subscript 0 to subscript 3 inclusive, resulting in the string "dcbaefd".Copy the code
  • Example 2
Input: word = "xyxzxe", ch = "z" Output: "zxyxxe" Explanation: the first and only occurrence of "z" is at subscript 3. Invert the character from subscript 0 to subscript 3, resulting in the string "zxyxxe".Copy the code
  • Example 3
Input: word = "abcd", ch = "z" Output: "abcd" Explanation: "z" does not exist in word. There is no need to reverse, and the resulting string is "abcd".Copy the code

prompt

  • 1 <= word.length <= 250
  • wordConsists of lowercase English letters
  • chIt’s a lowercase letter

solution

/ * * *@param {string} word

* @param {character} ch

* @return {string}* /

var reversePrefix = function(word, ch) {

// If it does not exist, only the original string is returned

if(word.indexOf(ch) == -1) return word;

// Invert the substring of the original array into the new array

// Then cut the last half of the array and concatenate, convert to a string for output

// console.log(word.indexOf(ch));

let index = word.indexOf(ch);

if(index == word.length - 1) return word.split(' ').reverse().join(' ');

let subStr = word.slice(0,index + 1);

// If you find the last one

return subStr.split(' ').reverse().join(' ') + word.slice(index + 1);

};
Copy the code