[LeetCode] Resulting String After Adjacent Removals

3561. Resulting String After Adjacent Removals

You are given a string s consisting of lowercase English letters.

You must repeatedly perform the following operation while the string s has at least two consecutive characters:

  • Remove the leftmost pair of adjacent characters in the string that are consecutive in the alphabet, in either order (e.g., 'a' and 'b', or 'b' and 'a').
  • Shift the remaining characters to the left to fill the gap.

Return the resulting string after no more operations can be performed.

Note: Consider the alphabet as circular, thus 'a' and 'z' are consecutive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
bool cons(char a, char b) {
int d = abs(a-b);
return d == 1 or d == 25;
}
public:
string resultingString(string s) {
string res = "";
for(auto& ch : s) {
if(res.length() and cons(res.back(), ch)) res.pop_back();
else res.push_back(ch);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/25/PS/LeetCode/resulting-string-after-adjacent-removals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.