feat: 反转单词前缀(2000)
This commit is contained in:
parent
fe8572dd0e
commit
dbecfb3b6b
41
leetcode/简单/反转单词前缀.js
Normal file
41
leetcode/简单/反转单词前缀.js
Normal file
@ -0,0 +1,41 @@
|
||||
/*
|
||||
2000. 反转单词前缀
|
||||
简单
|
||||
|
||||
相关标签
|
||||
相关企业
|
||||
|
||||
提示
|
||||
给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i ,反转 word 中
|
||||
从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。
|
||||
|
||||
例如,如果 word = "abcdefd" 且 ch = "d" ,那么你应该 反转 从下标 0 开始、直到下标 3 结束(含下标 3 )。结果字符串将会是 "dcbaefd" 。
|
||||
返回 结果字符串 。
|
||||
*/
|
||||
|
||||
/*
|
||||
思路:先找到字符出现的位置,之后设置两个瓜下表交换首尾字符即可
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} word
|
||||
* @param {character} ch
|
||||
* @return {string}
|
||||
*/
|
||||
const reversePrefix = function (word, ch) {
|
||||
const index = word.indexOf(ch);
|
||||
if (index < 0) return word;
|
||||
let left = 0;
|
||||
let right = index;
|
||||
const arr = [...word];
|
||||
while (left < right) {
|
||||
const tmp = arr[left];
|
||||
arr[left] = arr[right];
|
||||
arr[right] = tmp;
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
return arr.join('');
|
||||
};
|
||||
|
||||
console.log(reversePrefix('abcdefd', 'd'));
|
Loading…
x
Reference in New Issue
Block a user