删除字符串中的所有相邻重复项
生活随笔
收集整理的這篇文章主要介紹了
删除字符串中的所有相邻重复项
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種寫法
public:string removeDuplicates(string S) {stack<char> st;st.push(S[0]);for(int ii=1;ii<S.size();ii++){if(st.empty()||S[ii]!=st.top()) st.push(S[ii]);else st.pop();}S.resize(st.size());for(int ii=st.size()-1;ii>=0;ii--){S[ii]=st.top();st.pop();}return S;}};第二種寫法
class Solution { public:string removeDuplicates(string S) {stack<char> st;for(auto &n:S) {if((st.empty()) ||(st.top()!=n)) st.push(n);else st.pop();}S.resize(st.size());for(int i=st.size()-1;i>=0;i--){S[i]=st.top();st.pop();}return S;} };第三種寫法
class Solution { public:string removeDuplicates(string S) {//把string作為棧,可以省去排序操作string result;for(auto &s:S){if( (result.empty())||result.back()!=s) result.push_back(s); else result.pop_back();} return result;}};第四種
class Solution { public:string removeDuplicates(string S) {stack<char> st;string result="";for(auto &n:S) {if((st.empty()) ||(st.top()!=n)) st.push(n);else st.pop();}while(!st.empty()) //空返回1,非空返回0{//result.push_back(st.top());result+=st.top();st.pop();}reverse (result.begin(), result.end()); // 此時字符串需要反轉一下return result; } };總結
以上是生活随笔為你收集整理的删除字符串中的所有相邻重复项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 栈和队列的基础知识
- 下一篇: 校门外的树+矩阵旋转