Leetcode 917. Reverse Only Letters
Given a string s
, reverse the string according to the following rules:
Return s
after reversing it.
Q: Can the string s
be empty?
A: Yes, an empty string is a valid input and should be handled.
Q: Are there any constraints on the length of the string?
A: The string length will be between 1 and 100.
Q: Are the non-letter characters limited to specific ones like -
, =
, etc.?
A: No, any character that is not a letter should remain in its position.
left
) and one at the end (right
) of the string.left
pointer is less than right
pointer:
left
is not a letter, move the left
pointer to the right.right
is not a letter, move the right
pointer to the left.#include <iostream>
#include <string>
#include <cctype>
std::string reverseOnlyLetters(std::string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
// Move left pointer to the right if not a letter
if (!std::isalpha(s[left])) {
left++;
}
// Move right pointer to the left if not a letter
else if (!std::isalpha(s[right])) {
right--;
}
// Both are letters, so we swap them
else {
std::swap(s[left], s[right]);
left++;
right--;
}
}
return s;
}
// Test cases
int main() {
std::string s1 = "ab-cd";
std::string s2 = "a-bC-dEf-ghIj";
std::string s3 = "Test1ng-Leet=code-Q!";
std::cout << reverseOnlyLetters(s1) << std::endl; // Output: "dc-ba"
std::cout << reverseOnlyLetters(s2) << std::endl; // Output: "j-Ih-gfE-dCba"
std::cout << reverseOnlyLetters(s3) << std::endl; // Output: "Qedo1ct-eeLg=ntse-T!"
return 0;
}
This approach optimally handles the problem by using a clear and efficient strategy, making it suitable for the given constraints.
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?