本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。
为了方便在PC上运行调试、分享代码文件,我还建立了相关的仓库:https://github.com/memcpy0/LeetCode-Conquest。在这一仓库中,你不仅可以看到LeetCode原题链接、题解代码、题解文章链接、同类题目归纳、通用解法总结等,还可以看到原题出现频率和相关企业等重要信息。如果有其他优选题解,还可以一同分享给他人。
由于本系列文章的内容随时可能发生更新变动,欢迎关注和收藏征服LeetCode系列文章目录一文以作备忘。
Given a 0-indexed string word
and a character ch
, reverse the segment of word
that starts at index 0
and ends at the index of the first occurrence of ch
(inclusive). If the character ch
does not exist in word
, do nothing.
- For example, if
word = "abcdefd"
andch = "d"
, then you should reverse the segment that starts at0
and ends at3
(inclusive). The resulting string will be"dcbaefd"
.
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word
consists of lowercase English letters.ch
is a lowercase English letter.
题意:给你一个下标从 0 开始的字符串 word
和一个字符 ch
。找出 ch
第一次出现的下标 i
,反转 word
中从下标 0
开始、直到下标 i
结束(含下标 i
)的那段字符。如果 word
中不存在字符 ch
,则无需进行任何操作。
- 例如,如果
word = "abcdefd"
且ch = "d"
,那么你应该 反转 从下标 0 开始、直到下标3
结束(含下标3
)。结果字符串将会是"dcbaefd"
。
返回 结果字符串 。
解法 字符串
很简单的题目,竞赛中我的解法如下:
//C++ version
class Solution {
public:
string reversePrefix(string word, char ch) {
size_t pos = word.find_first_of(ch);
if (pos == string::npos) return word;
reverse(word.begin(), word.begin() + pos + 1);
return word;
}
};
//执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
//内存消耗:6.1 MB, 在所有 C++ 提交中击败了50.00% 的用户