Table of Contents
Description: 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"
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
1 2 3 4 |
<strong>Input:</strong> word = "abcdefd", ch = "d" <strong>Output:</strong> "dcbaefd" <strong>Explanation:</strong> The first occurrence of "d" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd". |
Example 2
1 2 3 4 |
<strong>Input:</strong> word = "xyxzxe", ch = "z" <strong>Output:</strong> "zxyxxe" <strong>Explanation:</strong> The first and only occurrence of "z" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe". |
Example 3
1 2 3 4 |
<strong>Input:</strong> word = "abcd", ch = "z" <strong>Output:</strong> "abcd" <strong>Explanation:</strong> "z" does not exist in word. You should not do any reverse operation, the resulting string is "abcd". |
Constraints
1 <= word.length <= 250
word
consists of lowercase English letters.ch
is a lowercase English letter.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Solution { public String reversePrefix(String word, char ch) { if(word==null || word.isBlank()){ return word; } //find the first index of ch in the word int end = word.indexOf(ch); if(end!=-1){ char[] c = word.toCharArray(); int left = 0; int right = end; //reverse the portion between 0 and the index of ch while(left<right){ char t = c[left]; c[left] = c[right]; c[right] = t; left++; right--; } word = new String(c); } return word; } } |
Time Complexity
O(n), where n is the number of characters in the word (specifically O(n/2))
Space Complexity
O(n), where n is the number of characters in the word