Process String with Special Operations II Problem
Description
LeetCode Problem 3614.
You are given a string s consisting of lowercase English letters and the special characters: '*', '#', and '%'.
You are also given an integer k.
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 k^th character of the final string result. If k is out of the bounds of result, return '.'.
Example 1:
Input: s = "a#b%*", k = 1
Output: "a"
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"
The final result is "ba". The character at index k = 1 is 'a'.
Example 2:
Input: s = "cd%#*#", k = 3
Output: "d"
Explanation:
i s[i] Operation Current result
0 'c' Append 'c' "c"
1 'd' Append 'd' "cd"
2 '%' Reverse result "dc"
3 '#' Duplicate result "dcdc"
4 '*' Remove the last character "dcd"
5 '#' Duplicate result "dcddcd"
The final result is "dcddcd". The character at index k = 3 is 'd'.
Example 3:
Input: s = "z*#", k = 0
Output: "."
Explanation:
i s[i] Operation Current result
0 'z' Append 'z' "z"
1 '*' Remove the last character ""
2 '#' Duplicate the string ""
The final result is "". Since index k = 0 is out of bounds, the output is '.'.
Constraints:
1 <= s.length <= 10^5sconsists of only lowercase English letters and special characters'*','#', and'%'.0 <= k <= 10^15- The length of
resultafter processingswill not exceed10^15.
Solution
Approach: Reverse Tracking
The result can be huge (up to 10^15 characters), so we never build it. First compute only its final length m by walking forward: a letter adds 1, * subtracts 1 (never below 0), # doubles, % changes nothing. If k >= m, return '.'.
Then walk s backwards, keeping k as the index in the string as it was just after each operation:
*: the character it removed was beyond the current end, somgrows by1.#: the string was two equal halves, somis halved, and ifk >= mwe movekinto the first half withk -= m.%: the string was reversed, sokbecomesm - 1 - k.- A letter:
mshrinks by1; ifk == m, this letter is the answer.
Complexity: O(n) time and O(1) extra space, where n = len(s).
class Solution:
def processStr(self, s: str, k: int) -> str:
m = 0
for c in s:
if c == "*":
m = max(0, m - 1)
elif c == "#":
m <<= 1
elif c != "%":
m += 1
if k >= m:
return "."
for c in reversed(s):
if c == "*":
m += 1
elif c == "#":
m //= 2
if k >= m:
k -= m
elif c == "%":
k = m - 1 - k
else:
m -= 1
if k == m:
return c