Given a string s, reverse the string according to the following rules:
Return s after reversing it.
Example 1:
Input: s = "ab-cd" Output: "dc-ba"
Example 2:
Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"
Example 3:
Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"
Constraints:
1 <= s.length <= 100s consists of characters with ASCII values in the range [33, 122].s does not contain '\"' or '\\'.Using a two-pointer technique, we can efficiently reverse only the letters in the string. One pointer starts from the beginning and the other from the end. We swap letters when both pointers are on valid letters. If a pointer is on a non-letter, it moves until it finds a letter. The process continues until the two pointers meet or cross each other.
This C function uses two pointers to reverse letters in a string. The isalpha() function checks for letters, and strlen() gives the length to set the right pointer. A simple swap operation is done when both pointers point to letters.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we are modifying the string in place.
This approach uses a stack to collect all the letters in the string and then reinserts them in reverse order while iterating through the original string.
C solution employs a manual stack using an array to reverse letters. The letters are first pushed into the stack and then popped off when reinserting into the original string.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), for iterating through the string twice.
Space Complexity: O(n), for storing letter characters in the stack.
| Approach | Complexity |
|---|---|
| Two Pointer Approach | Time Complexity: O(n), where n is the length of the string. |
| Stack-Based Approach | Time Complexity: O(n), for iterating through the string twice. |
Reverse Only Letters • Kevin Naughton Jr. • 16,578 views views
Watch 9 more video solutions →Practice Reverse Only Letters with our built-in code editor and test cases.
Practice on FleetCode