[LeetCode] Process String with Special Operations II

3614. Process String with Special Operations II

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 from result, if it exists.
  • A '#' duplicates the current result and appends it to itself.
  • A '%' reverses the current result.

Return the kth character of the final string result. If k is out of the bounds of result, return '.'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

class Solution {
public:
char processStr(string s, long long k) {
long long len = 0, ma = 4e18;
vector<long long> lens;
for(auto& ch : s) {
if(isalpha(ch)) len++;
else if(ch == '*') len = max(len - 1, 0ll);
else if(ch == '#') len = min(len * 2, ma);

lens.push_back(len);
}

if(len <= k or len == 0) return '.';

for(int i = s.length() - 1; i >= 0; i--) {
if(isalpha(s[i])) {
if(lens[i] - 1 == k) return s[i];
} else if(s[i] == '#') {
k = k % (lens[i] / 2);
} else if(s[i] == '%') {
k = lens[i] - k - 1;
}
}
return '#';
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/14/PS/LeetCode/process-string-with-special-operations-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.