---------------🎈🎈题目链接🎈🎈-------------------
如果栈顶元素和当前的字符相同,就弹出栈顶元素
如果不相同就把当前字符push进栈中
最终输出栈中剩下的元素为字符串形式
时间复杂度O(N)
空间复杂度O(N)
class Solution {
public String removeDuplicates(String s) {
Stack<Character> mystack = new Stack<>();
for(int i = 0; i<s.length(); i++){
char mychar = s.charAt(i);
if(!mystack.isEmpty() && mystack.peek()== mychar){
mystack.pop();
continue;
}
mystack.push(mychar);
}
String result = new String();
result = "";
while(!mystack.isEmpty()){
result = mystack.pop() + result;
}
return result;
}
}
首先将字符串转化为字符串数组:char chararray = s.toCharArray();
使用fast和slow两个指针,当遇到slow和fast指针指向的字符相同时,则slow–,fast++
其余时候只需要ch[slow] = ch[fast] 覆盖操作即可,之后slow++, fast++
最后将索引0到slow的字符串数组转化为字符串:String resultString = new String(chararray, 0, slow)
时间复杂度O(N)
空间复杂度O(1)
class Solution {
public String removeDuplicates(String s) {
char[] ch = s.toCharArray();
int fast = 0;
int slow = 0;
while(fast < s.length()){
ch[slow] = ch[fast];
if(slow > 0 && ch[slow] == ch[slow-1]){
slow--;
fast++;
continue;
}
slow++;
fast++;
}
String result = new String(ch,0,slow);
return result;
}
}