diff options
author | Jack Sangdahl <[email protected]> | 2025-06-05 23:29:14 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-06-05 23:29:14 -0600 |
commit | 285b89a7d901268035bc0faf199b7a5c64f5d787 (patch) | |
tree | 713ce95e55469e53d3886a48da61cf353835966b /res_str_adj_remove.py | |
parent | 79c7e9462c5cb51657167f9412b5c3711a5d8a61 (diff) | |
download | leetcode-285b89a7d901268035bc0faf199b7a5c64f5d787.tar.gz leetcode-285b89a7d901268035bc0faf199b7a5c64f5d787.zip |
3561. resulting string after adjacent removals
Diffstat (limited to 'res_str_adj_remove.py')
-rw-r--r-- | res_str_adj_remove.py | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/res_str_adj_remove.py b/res_str_adj_remove.py new file mode 100644 index 0000000..2949e18 --- /dev/null +++ b/res_str_adj_remove.py @@ -0,0 +1,38 @@ +# 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, and +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. +""" + + +class Solution(object): + def resultingString(self, s): + """ + :type s: str + :rtype: str + """ + ans = [] + + def helper(a): + c = abs(ord(ans[-1]) - ord(a)) + return c == 1 or c == 25 + + for i in s: + if ans and helper(i): + ans.pop() + else: + ans.append(i) + return "".join(ans) + + +if __name__ == "__main__": + obj = Solution() + print(obj.resultingString(s="abc")) + print(obj.resultingString(s="adcb")) + print(obj.resultingString(s="zadb")) |