Reverse Letters Then Special Characters in a String Problem
#3823
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3823.
You are given a string s consisting of lowercase English letters and special characters.
Your task is to perform these in order:
- Reverse the lowercase letters and place them back into the positions originally occupied by letters.
- Reverse the special characters and place them back into the positions originally occupied by special characters.
Return the resulting string after performing the reversals.
Example 1:
Input: s = ")ebc#da@f("
Output: "(fad@cb#e)"
Explanation:
- The letters in the string are ['e', 'b', 'c', 'd', 'a', 'f']:
- Reversing them gives ['f', 'a', 'd', 'c', 'b', 'e']
- s becomes ")fad#cb@e("
- The special characters in the string are [')', '#', '@', '(']:
- Reversing them gives ['(', '@', '#', ')']
- s becomes "(fad@cb#e)"
Example 2:
Input: s = "z"
Output: "z"
Explanation:
The string contains only one letter, and reversing it does not change the string. There are no special characters.
Example 3:
Input: s = "!@#$%^&*()"
Output: ")(*&^%$#@!"
Explanation:
The string contains no letters. The string contains all special characters, so reversing the special characters reverses the whole string.
Constraints:
1 <= s.length <= 100sconsists only of lowercase English letters and the special characters in"!@#$%^&*()".
Solution
Approach: Simulation
Scan s once and put the letters into a list a and the special characters into a list b, both in order. Then scan s again: at a letter position put back the last unused letter of a (pop it), and at a special-character position put back the last unused character of b. Because the lists are consumed from the end, each group comes out reversed while staying in its own positions.
Complexity: O(n) time and O(n) space, where n is the length of s.
class Solution:
def reverseByType(self, s: str) -> str:
a = []
b = []
for c in s:
if c.isalpha():
a.append(c)
else:
b.append(c)
return ''.join(a.pop() if c.isalpha() else b.pop() for c in s)