- Published on
Reverse Prefix of Word.
Problem of the day - Reverse Prefix of Word
Tag - Easy
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".
I had a couple of thought in mind. How about find the index of char and reverse the sub-string and concat it. But it seems, very slow algo.
To reverse the string, I came up the approach of swapping elements. Pretty basic stuff.
class Solution {public: string reversePrefix(string word, char ch) { int char_index = -1; char temp; for(int i=0;i<word.length();i++) { if(word[i] == ch) { char_index = i; break; } }
// if not found if(char_index == -1) return word;
// swap elements for(int i=0;i<=char_index / 2;i++) { temp = word[i]; word[i] = word[char_index - i]; word[char_index - i] = temp; } return word; }};
If you feel, I am missing on something, feel free to reach out to me
I welcome your suggestions to improve it further!
Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.
You might like previous editions of my coding diary
- Day #33 - Word Pattern.
- Day #32 - Remove Outermost Parentheses.
- Day #31 - Check if Numbers Are Ascending in a Sentence.
- Day #30 - Finding the Users Active Minutes.
- Day #29 - Product of array except self.
- Day #28 - Convert 1D Array Into 2D Array.
- Day #27 - Minimum Moves to Convert String.
- Day #26 - Two Out of Three.