LeetCode 2000: Reverse Prefix of Word Solution
Master LeetCode problem 2000 (Reverse Prefix of Word), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2000. Reverse Prefix of Word
Problem Explanation
Explanation
To solve this problem, we need to find the index of the first occurrence of the character ch in the given word string. If ch is not found, we do nothing and return the original word. Otherwise, we reverse the segment of word starting from index 0 up to the index of the first occurrence of ch. We can achieve this by using a two-pointer approach where one pointer iterates from the beginning of the string and the other pointer moves until we find the first occurrence of ch. Once we have the index, we reverse the substring using the two pointers.
- Start with two pointers
startat 0 andendat -1. - Iterate through the
worduntil we find the first occurrence ofch. - Reverse the substring from index 0 to the index of
ch.
The time complexity of this solution is O(n) where n is the length of the word string. The space complexity is O(n) for storing the characters of the word string.
Solution Code
class Solution {
public String reversePrefix(String word, char ch) {
int end = word.indexOf(ch);
if (end == -1) {
return word;
}
char[] chars = word.toCharArray();
int start = 0;
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
return new String(chars);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2000 (Reverse Prefix of Word)?
This page provides optimized solutions for LeetCode problem 2000 (Reverse Prefix of Word) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2000 (Reverse Prefix of Word)?
The time complexity for LeetCode 2000 (Reverse Prefix of Word) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2000 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2000 in Java, C++, or Python.