[LeetCode] Reverse Prefix of Word

2000. Reverse Prefix of Word

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" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

Return the resulting string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string reversePrefix(string word, char ch) {
int idx = -1;
for(int i = 0; i < word.size(); i++) {
if(word[i] == ch) {
idx = i;
break;
}
}
if(idx != -1) {
reverse(begin(word), begin(word) + idx + 1);
}
return word;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/01/PS/LeetCode/reverse-prefix-of-word/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.