
Problem Statement
In this problem, we are given a string word
that begins at the 0th index, and a character ch
. The goal is to reverse the portion of word
from the start (0-index) to the position where the character ch
first appears, including that character's position. If the specified character ch
does not appear at all within word
, then the string remains unchanged. After performing this operation, the resulting string should be returned. This manipulation challenges us to identify and modify specific segments of a string based on character occurrence, providing insight into string handling and the reversal process in programming.
Examples
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".
Example 2
Input:
word = "xyxzxe", ch = "z"
Output:
"zxyxxe"
Explanation:
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
Input:
word = "abcd", ch = "z"
Output:
"abcd"
Explanation:
"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.
Approach and Intuition
To solve the problem efficiently, let's follow these steps:
Search for the Character:
- Check if the character
ch
is present in theword
. - If found, record the index of its first occurrence (
indexCh
).
- Check if the character
Conditionally Reverse the Segment:
- If
ch
is not found, the string remains as is, and can be returned immediately. - If
ch
is found, split the string into two parts:- The part from the start of the
word
toindexCh
. - The remaining part from
indexCh+1
to the end.
- The part from the start of the
- Reverse the first part.
- If
Concatenate and Return:
- Concatenate the reversed segment with the unchanged latter part of the string to form the final result.
Key Points:
- Only the sub-sequence from the start of the string to the first occurrence of
ch
is modified. - The rest of the string remains unchanged.
- If
ch
is absent in the string, no operations are required.
Example walkthroughs illustrate how this approach is directly applied:
- In the first example with
word = "abcdefd"
andch = "d"
, the reversal occurs up to the first'd'
at index 3, transforming "abcd" to "dcba" and resulting in "dcbaefd". - If the character
ch
does not exist in the string as in the third example whereword = "abcd"
andch = "z"
, the output remains "abcd" because no reversal is necessary.
Solutions
- C++
class Solution {
public:
string reversePrefix(string str, char delimiter) {
int startIndex = 0;
for (int endIndex = 0; endIndex < str.length(); endIndex++) {
if (str[endIndex] == delimiter) {
while (startIndex < endIndex) {
swap(str[startIndex], str[endIndex]);
startIndex++;
endIndex--;
}
return str;
}
}
return str;
}
};
The provided C++ solution is designed to reverse the prefix of a string up until a specified delimiter character. The function reversePrefix
, defined within the Solution
class, accepts two arguments: a string str
and a character delimiter
.
Follow these general steps to understand the implementation:
- Initialize
startIndex
to 0 to track the beginning of the string. - Use a
for
loop with a variableendIndex
iterating over the string to locate the delimiter character. - When the delimiter is found, engage a nested loop that swaps characters from
startIndex
toendIndex
, effectively reversing the segment. - Increment
startIndex
and decrementendIndex
concurrently within the loop to move towards the center from both ends, ensuring the substring's characters are reversed. - Upon completing the reversal or if the delimiter is not found, the modified string is returned.
This function makes a direct modification to the input string and handles the scenario where the delimiter does not exist by returning the string unchanged. The approach is efficient, leveraging in-place character swaps to perform the reversal without needing additional memory for substring manipulation.
- Java
public class Solution {
public String reversePrefix(String str, char delimiter) {
char[] arr = str.toCharArray();
int start = 0;
for (int end = 0; end < str.length(); end++) {
if (arr[end] == delimiter) {
while (start < end) {
charSwap(arr, start, end);
start++;
end--;
}
return new String(arr);
}
}
return str;
}
private void charSwap(char[] array, int pos1, int pos2) {
char hold = array[pos2];
array[pos2] = array[pos1];
array[pos1] = hold;
}
}
The provided Java code aims to reverse the prefix of a word up to a specified delimiter character and return the modified string. The method reversePrefix
takes two parameters: a string str
and a character delimiter
. It reverses the sequence of characters in str
from the beginning up to the first occurrence of delimiter
.
Steps for Execution:
Convert string
str
to a character arrayarr
to facilitate character swapping.Initialize an integer
start
to track the beginning of the substring to reverse.Use a loop where
end
iterates through the characters inarr
. Inside the loop, check if the current character matches thedelimiter
.If a match is found, use another loop to swap characters from
start
toend
until they meet, effectively reversing the order of characters in that segment.Return the newly formed string constructed from array
arr
after the reversal.
If
delimiter
is not found instr
, the method returns the original string unchanged.
The helper method charSwap
aids in swapping characters in the array arr
by taking the array itself and two positions (pos1
and pos2
) of characters to swap. This method performs the swap by utilizing a temporary placeholder.
Ensure you handle edge cases such as scenarios where:
- The
delimiter
does not exist instr
. - The
delimiter
is at the start or end ofstr
. - The
str
is empty or contains only one character.
By implementing the above mechanism, this Java solution efficiently handles the task of selectively reversing parts of a string based on a given delimiter.
- Python
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
seq = list(word)
start = 0
for end in range(len(word)):
if seq[end] == ch:
while start < end:
seq[end], seq[start] = seq[start], seq[end]
start += 1
end -= 1
return "".join(seq)
return word
In the Python solution provided for "Reverse Prefix of Word," a method reversePrefix
is implemented within a Solution
class. The method takes two parameters: word
, a string, and ch
, a character. It aims to reverse the portion of word
that precedes the first occurrence of ch
.
Follow these steps to understand the functionality:
- Convert the input string
word
into a listseq
to facilitate in-place modifications. - Initialize
start
to 0 to track the beginning of the sequence to reverse. - Iterate over the indices (
end
) of the sequence. - Check if the current character matches
ch
. - If a match is found, use a while loop to reverse the segment from
start
toend
:- Swap characters at positions
start
andend
. - Increment
start
and decrementend
to progressively narrow down the focused segment.
- Swap characters at positions
- Once the segment is reversed, or if
ch
is not found inword
, convert the list back to a string and return it.
This approach efficiently locates and reverses the required segment and then immediately returns the modified word.
No comments yet.