Leetcode 2000 Reverse Prefix of Word Solution in c++ | Hindi Coding Community

0

 


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.


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".




class Solution {
public:
string reversePrefix(string word, char ch)
{
int index=-1;
for(int i=0;i<word.size();i++)
{
if(word[i]==ch)
{
index=i;
break;
}
}
if(index!=-1)
{
reverse(word.begin(),word.begin()+index+1);
}
return word;
}
};


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !