给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i ,反转 word 中从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。
例如,如果 word = “abcdefd” 且 ch = “d” ,那么你应该 反转 从下标 0 开始、直到下标 3 结束(含下标 3 )。结果字符串将会是 “dcbaefd” 。
返回 结果字符串 。
示例 1:
输入:word = “abcdefd”, ch = “d”
输出:“dcbaefd”
解释:“d” 第一次出现在下标 3 。
反转从下标 0 到下标 3(含下标 3)的这段字符,结果字符串是 “dcbaefd” 。
提示:
1 <= word.length <= 250
word 由小写英文字母组成
ch 是一个小写英文字母
解法一:直接模拟即可:
class Solution {
public:
string reversePrefix(string word, char ch) {
int firstAppearIndex = 0;
int wordSize = word.size();
for (int i = 0; i < wordSize; ++i) {
if (word[i] == ch) {
firstAppearIndex = i;
break;
}
}
int loopNum = (firstAppearIndex + 1) >> 1;
for (int i = 0; i < loopNum; ++i) {
swap(word[i], word[firstAppearIndex - i]);
}
return word;
}
};
如果输入字符串word的长度为n,此算法时间复杂度为O(n),空间复杂度为O(1)。
解法二:使用库函数:
class Solution {
public:
string reversePrefix(string word, char ch) {
int firstAppearIndex = word.find(ch);
if (firstAppearIndex != string::npos) {
reverse(word.begin(), word.begin() + firstAppearIndex + 1);
}
return word;
}
};
如果输入字符串word的长度为n,此算法时间复杂度为O(n),空间复杂度为O(1)。