Topics requirements:
String S is given by the lowercase letters, delete duplicates and selects two identical letters adjacent to, and remove them
repeatedly performed in duplicate S delete, delete can not continue until
completion of all delete duplicates after returning final string. The only answer guarantee
Example:
Input: "abbaca"
Output: "ca"
solution
Method One: Use stack ideas
class Solution {
public String removeDuplicates(String S) {
if(S==null||S=="") return S;//特殊情况
StringBuilder res=new StringBuilder();//栈
int top=-1;//栈顶
for(char c:S.toCharArray()){
if(top==-1||res.charAt(top)!=c){//匹配不成功两种情况:栈为空,n不相等
res.append(c);
top++;
}
else{
res.deleteCharAt(top);//已经匹配,删除改字符
top--;
}
}
return res.toString();
}
}
/*
str.toCharArray()
sb.charAt()
sb.deleteCharAt()
*/
Method two: the original step algorithm (for cpp)
class Solution {
public:
string removeDuplicates(string S) {
int top = 0;
for (char ch : S) {
if (top == 0 || S[top - 1] != ch) {
S[top++] = ch;
} else {
top--;
}
}
S.resize(top);
return S;
}
};