Leetcode 2000 Reverse Prefix of Word in java | 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)
{
char[] chArray = word.toCharArray();

int idx;
for(idx=0; idx<chArray.length; idx++)
{
if(chArray[idx] == ch) break;
}

if(idx == chArray.length) return word;

for(int left=0, right=idx; left<right; left++, right--)
{
char temp = chArray[left];
chArray[left] = chArray[right];
chArray[right] = temp;
}
return new String(chArray);
}
}

Post a Comment

0Comments
Post a Comment (0)

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

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