LeetCode 917: Reverse Only Letters Solution
Master LeetCode problem 917 (Reverse Only Letters), 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.
917. Reverse Only Letters
Problem Explanation
Explanation
To solve this problem, we can use a two-pointer approach. We will have one pointer starting from the beginning of the string and another pointer starting from the end of the string. We will iterate over the string and swap characters at the two pointers if they are both English letters. If one or both characters are not English letters, we will skip them and move the respective pointers.
- Time complexity: O(n) where n is the length of the input string
- Space complexity: O(n) for storing the characters in the resulting string
Solution Code
class Solution {
public String reverseOnlyLetters(String s) {
char[] chars = s.toCharArray();
int left = 0, right = s.length() - 1;
while (left < right) {
if (!Character.isLetter(chars[left])) {
left++;
} else if (!Character.isLetter(chars[right])) {
right--;
} else {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
return new String(chars);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 917 (Reverse Only Letters)?
This page provides optimized solutions for LeetCode problem 917 (Reverse Only Letters) 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 917 (Reverse Only Letters)?
The time complexity for LeetCode 917 (Reverse Only Letters) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 917 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 917 in Java, C++, or Python.