Medium
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:
'a'
and 'b'
, or 'b'
and 'a'
).Return the resulting string after no more operations can be performed.
Note: Consider the alphabet as circular, thus 'a'
and 'z'
are consecutive.
Example 1:
Input: s = “abc”
Output: “c”
Explanation:
"ab"
from the string, leaving "c"
as the remaining string."c"
.Example 2:
Input: s = “adcb”
Output: “”
Explanation:
"dc"
from the string, leaving "ab"
as the remaining string."ab"
from the string, leaving ""
as the remaining string.""
.Example 3:
Input: s = “zadb”
Output: “db”
Explanation:
"za"
from the string, leaving "db"
as the remaining string."db"
.Constraints:
1 <= s.length <= 105
s
consists only of lowercase English letters.public class Solution {
public String resultingString(String s) {
int n = s.length();
int p = 0;
char[] buf = new char[n];
for (char c : s.toCharArray()) {
if (p > 0) {
int d = buf[p - 1] - c;
int ad = d < 0 ? -d : d;
if (ad == 1 || ad == 25) {
p--;
continue;
}
}
buf[p++] = c;
}
return new String(buf, 0, p);
}
}