首页 > 其他分享 >1047. 删除字符串中的所有相邻重复项

1047. 删除字符串中的所有相邻重复项

时间:2023-03-27 19:44:41浏览次数:37  
标签:1047 sta 删除 res len 相邻 字符串 size string

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

class Solution {
public:
    using size = string::size_type;
    string removeDuplicates(string s) {
        size len = s.size();
        std::stack<char> sta;
        for (size i = 0; i != len; i++)
        {
            if (!sta.empty())
            {
                char tmp = sta.top();
                if (tmp == s[i])
                {
                    sta.pop();
                    continue;
                }
            }
            sta.push(s[i]);
        }
        string res;
        while (!sta.empty()) { // 将栈中元素放到result字符串汇总
            res += sta.top();
            sta.pop();
        }
        std::reverse(res.begin(), res.end()); // 此时字符串需要反转一下
        return res;
    }
    string removeDuplicates1(string s) {
        size len = s.size();
        for (size i = 0; i != len;)
        {
            if (i >= 1 && s[i] == s[i - 1])
            {
                s.erase(i - 1,1);
                s.erase(i - 1,1);
                len = s.size();
                i--;
            }
            else {
                i++;
            }
        }
        return s;
    }
};

标签:1047,sta,删除,res,len,相邻,字符串,size,string
From: https://www.cnblogs.com/lihaoxiang/p/17262620.html

相关文章

  • Python字符串学习
    if__name__=="__main__"是Python中常见的代码块,通常用于控制Python程序的执行流程。这个代码块可以保证一些特定的代码仅在当前模块被直接执行时运行,而不会在模块......
  • 实验2 字符串和列表
    1.试验任务11x='nbaFIFA'2print(x.upper())#字符串转大写3print(x.lower())#字符串转小写4print(x.swapcase())#字符串大小写互换5print()6......
  • 实验二 字符串和列表
    任务一源代码:1#字符串的基础操作2#课堂上没有演示的一些方法34x='nbaFIFA'5print(x.upper())#字符串转大写6print(x.lower())#字符串转小......
  • 实验2 字符串和列表
    一、实验任务1.实验任务1程序源代码:x='nbaFIFA'print(x.upper())print(x.lower())print(x.swapcase())print()x='abc'print(x.center(10,"*"))print(x.ljus......
  • 实验二:字符串和列表
         试验任务一 task1  代码:x='nbaFIFA'print(x.upper())print(x.lower())print(x.swapcase())print()x='abc'print(x.center(10,'*'))p......
  • 实验二 字符串和列表
    实验任务1task1.py1#字符串的基础操作2#课堂上没有演示的一些方法34x='nbaFIFA'5print(x.upper())6print(x.lower())7print(x.swapcase())8......
  • C语言—字符函数和字符串函数解析及其模拟实现
    目录一、求字符串的长度1、strlen()-字符串长度二、长度不受限制的字符串函数1、strcpy()-字符串拷贝2、strcat()-字符串追加3、strcmp()-字符串比较三、长度受限制的字符串函数1、s......
  • c#动态执行字符串脚本(优化版)
    像javascript中有eval()来执行动态代码,c#中是没有的,于是自己动手丰衣足食,先来代码1usingSystem;2usingSystem.Data;3usingSystem.Configuration;4us......
  • 【DP】LeetCode 剑指 Offer 46. 把数字翻译成字符串
    题目链接剑指Offer46.把数字翻译成字符串思路这个问题与dp中的经典问题“跳台阶”问题十分类似,在跳台阶问题中我们是选择跳一个台阶或者两个台阶,而在这个问题中我......
  • 前端传递Base64字符串,后端转流存入OSS
    工具类publicstaticBufferedInputStreambase64Convert(Stringbase64){//解码base64=base64.split(",")[1];try{byte[]......