Leetcode 2000. Reverse Prefix of Word
You are given a 0-indexed string word
and a character ch
. Find the first occurrence of ch
in word
, and reverse the segment of word
that starts at index 0
and ends at the index of the first occurrence (inclusive). If the character ch
does not exist in word
, return the original string.
word = "abcdefd", ch = 'd'
"dcbaefd"
Q: Are there any constraints on the length of the word
or the type of characters it can contain?
A: 1 <= word.length <= 250
, word
consists of only lowercase English letters, and ch
is a lowercase English letter.
Q: What should be done if ch
is not found in word
?
A: The original word
should be returned.
Q: Should I consider the possibility of multiple occurrences of the character ch
?
A: Only the first occurrence of ch
should be considered.
ch
:
indexOf
method to find the first occurrence of ch
in the word
.ch
is found, use string manipulation to reverse the substring from the start to the found index.public class Solution {
public String reversePrefix(String word, char ch) {
int index = word.indexOf(ch);
if (index == -1) {
return word;
}
String prefix = new StringBuilder(word.substring(0, index + 1)).reverse().toString();
String suffix = word.substring(index + 1);
return prefix + suffix;
}
}
indexOf
method runs in O(n) time where n
is the length of the string.k
is the length of the substring (from start to the first occurrence of ch
).Overall, the time complexity for the operation is O(n).
This strategy and implementation ensure that the solution is efficient and meets the problem constraints effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?