Description
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. - 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:
i |
s[i] |
Operation | Current result |
|---|---|---|---|
| 0 | 'a' |
Append 'a' |
"a" |
| 1 | '#' |
Duplicate result |
"aa" |
| 2 | 'b' |
Append 'b' |
"aab" |
| 3 | '%' |
Reverse result |
"baa" |
| 4 | '*' |
Remove the last character | "ba" |
Thus, the final result is "ba".
Example 2:
Input: s = "z*#"
Output: ""
Explanation:
i |
s[i] |
Operation | Current result |
|---|---|---|---|
| 0 | 'z' |
Append 'z' |
"z" |
| 1 | '*' |
Remove the last character | "" |
| 2 | '#' |
Duplicate the string | "" |
Thus, the final result is "".
Constraints:
1 <= s.length <= 20sconsists of only lowercase English letters and special characters*,#, and%.
Solutions
Solution using a string.
Language: javascript(2026-06-16 06:47)DONE
CPU Performance81.48%
Memory Performance74.07%
/**
* @param {string} s
* @return {string}
*/
var processStr = function(s) {
let reversed = false;
let res = '';
for (const char of s) {
if (char === '*') {
if (reversed) {
res = res.slice(1);
} else {
res = res.slice(0, res.length - 1);
}
} else if (char === '#') {
res = res + res;
} else if (char === '%') {
reversed = !reversed;
} else {
if (reversed) {
res = char + res;
} else {
res += char;
}
}
}
return reversed ? res.split('').reverse().join('') : res;
};