跳至主要內容

1047. Remove All Adjacent Duplicates In String


1047. Remove All Adjacent Duplicates In Stringopen in new window

🟢   🔖  字符串  🔗 LeetCodeopen in new window

题目

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = "abbaca"

Output: "ca"

Explanation:

For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Example 2:

Input: s = "azxxzy"

Output: "ay"

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters.

题目大意

给出由小写字母组成的字符串  S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 S 上反复执行重复项删除操作,直到无法继续删除。在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

解题思路

用栈模拟,类似“对对碰”;

  • 遍历输入的字符串,用栈来存储字符;
  • 如果栈不为空,且新遍历到的字符与栈顶的字符一样的话,就弹出栈顶字符;
  • 否则将新遍历到的字符放入栈顶;
  • 直至扫完整个字符串,栈中剩下的字符串就是最终要输出的结果。

代码

/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicates = function (s) {
	let stack = [];
	for (let i = 0; i < s.length; i++) {
		let len = stack.length;
		if (len != 0 && stack[len - 1] == s[i]) {
			stack.pop();
		} else {
			stack.push(s[i]);
		}
	}
	return stack.join('');
};

相关题目

相关题目
- [1209. 删除字符串中的所有相邻重复项 II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii)
- [2390. 从字符串中移除星号](https://leetcode.com/problems/removing-stars-from-a-string)
- [2716. 最小化字符串长度](https://leetcode.com/problems/minimize-string-length)