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”.
和1544题如出一辙,都是删除相邻的重复字母,从左到右只删除相邻的2个。
思路:
和1544题一样,从左到右遍历,用stack保存字母,
遇到相同的字母出栈(pop),否则压栈(push)。
这里用一个数组模拟stack,更高效。
public String removeDuplicates(String s) {
int n = s.length();
char[] st = new char[n];
char[] arr = s.toCharArray();
int top = -1;
for(char ch : arr) {
if(top >= 0 && ch == st[top]) {
top --;
} else {
st[++top] = ch;
}
}
return String.copyValueOf(st, 0, top+1); //最后一个参数是offset, 也就是substring的长度,top是0为起点的,所以要+1
}
这篇博客介绍了一个字符串处理问题,即如何删除所有相邻且相等的字符。通过遍历字符串并使用栈来跟踪不重复的字符,可以实现这一目标。示例中给出了输入字符串abbaca的处理过程,最终结果为ca。该算法确保了唯一性。
593

被折叠的 条评论
为什么被折叠?



