Process String with Special Operations I
Problem Statement
You are given a string s consisting of lowercase English letters and the special characters: *, #, and %.
Build a new string result by processing s according to the following rules from left to right:
- If the letter is a lowercase English letter, append it to
result. - A
*removes the last character fromresult, if it exists (backspace). - A
#duplicates the currentresultand appends it to itself. - A
%reverses the currentresult.
Return the final string result after processing all characters in s.
Example 1:
- Input:
s = "a#b%*" - Output:
"ba" - Explanation:
'a'-> Append:"a"'#'-> Duplicate:"aa"'b'-> Append:"aab"'%'-> Reverse:"baa"'*'-> Remove last:"ba"
Example 2:
- Input:
s = "z*#" - Output:
"" - Explanation:
'z'-> Append:"z"'*'-> Remove last:""'#'-> Duplicate:""
Video Explanation

Approach: Simulation
Since the constraints on the length of the string are extremely small (), we can solve this by directly simulating the operations using a dynamic array, list, or string builder depending on the language.
- Maintain an empty
resultstructure. - Iterate through each character of the input string
s. - Based on the character, perform the respective operation:
- Lowercase letter (
a-z): Add to the end of theresult. - Asterisk (
*): Pop the last element (make sure to check if theresultis not empty first). - Hash (
#): Concatenate the currentresultto itself. - Percent (
%): Reverse the characters in theresult.
- Lowercase letter (
- Once the loop finishes, return the final
resultcasted back to a string.
Using a list or character array is typically more efficient for these operations than manipulating immutable strings directly, especially for the reverse and duplicate steps.