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.class Solution {
fun resultingString(s: String): String {
val n = s.length
var p = 0
val buf = CharArray(n)
for (c in s.toCharArray()) {
if (p > 0) {
val d = buf[p - 1].code - c.code
val ad = if (d < 0) -d else d
if (ad == 1 || ad == 25) {
p--
continue
}
}
buf[p++] = c
}
return String(buf, 0, p)
}
}