简介

如果能想到栈的话,说明你的基础足够扎实。
我没有想到,我想到的是双向链表。我就是一个弟弟

思路

两个前后指针指向一个双向循环链表,然后判断是否相等相等的话,前一个指针前移,后一个指针后移,中间的删除。

code

#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <string.h>
using namespace std;
#define ll long long
#define mod (long long)(1e9+7)
class Solution1047 {
public:
    struct node {
        char val;
        node * pre;
        node * last;
    };
    string removeDuplicates(string S) {
        // Rebuild the structure
        node *head = new node();
        node *p = nullptr;
        head->val = 255;
        head->pre = nullptr;
        head->last = nullptr;
        for(int i=0; i<S.size(); i++) {
            node * t = new node();
            t->val = S[i];
            if(i == 0) {
                t->pre = head;
                t->last = nullptr;
                head->last = t;
            }else {
                t->pre = p;
                t->last = nullptr;
                p->last = t;
            }
            p = t;
        }
        p->last = head;
        bool check = true;
        node * q = head->last;
        p = head->last->last;
        node * t = nullptr;
        while(!(p == head)) {
            if(p->val == q->val) {
                t = q;
                q = q->pre;
                delete(t);
                
                t = p;
                p = p->last;
                delete(t);
                
                q->last = p;
                p->pre = q;
            }else{
                q = q->last;
                p = p->last;
            }
        }
        string rlt;
        t = head->last;
        while(t!=head) {
            rlt.push_back((char)t->val);
            t = t->last;
        }
        if(rlt.length() == 0) rlt = "";
        return rlt;
    }
};

参考链接

https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/solution/zhan-jing-dian-ti-mu-si-lu-qing-xi-cjian-ji-dai-ma/
给出的解决方案就是用栈来实现解决方案,简单直接明了

code

class Solution {
public:
    string removeDuplicates(string S) {
        string result;
        for(char s : S) {
            if(result.empty() || result.back() != s) {
                result.push_back(s);
            }
            else {
                result.pop_back();
            }
        }
        return result;
    }
};

posted on 2021-03-09 23:23  HDU李少帅  阅读(141)  评论(0编辑  收藏  举报