从字符串中删除计数大于或等于突发长度的相邻重复项

如何解决从字符串中删除计数大于或等于突发长度的相邻重复项

给出一个包含重复字符和突发长度的字符串,输出该字符串,以使字符串中相同相邻字符的数量小于突发长度。

输入:abbccccdd,burstLen = 3
正确的输出:abbdd
我的输出:abbd


输入:abbcccdeaffff,burstLen = 3
正确的输出:abbdea
我的输出:修道院

//Radhe krishna ki jytoi alokik
#include <bits/stdc++.h>
using namespace std;

string solve(string s,int burstLen)
{
    stack<pair<char,int>> ms;
    
    for (int i = 0; i < s.size(); i++)
    {
        if (!ms.empty() && ms.top().first == s[i])
        {
            int count = ms.top().second;
            ms.push({s[i],count + 1});
        }
        
        else
        {
            if(ms.empty() == true  ||  ms.top().first != s[i])
            {
                if(!ms.empty() && ms.top().second >= burstLen)
                {
                    int count = ms.top().second;
                    
                    while(!ms.empty() && count--)
                        ms.pop();
                    //(UPDATE)
                     ms.push({s[i],1});
                }
                
                else
                    ms.push({s[i],1});
            }
        }

    }
    
    if(!ms.empty() and ms.top().second >= burstLen)
    {
        int count = ms.top().second;
        while(!ms.empty() && count--)
            ms.pop();
    }

    string ans = "";
    while (!ms.empty())
    {
        ans += ms.top().first;
        ms.pop();
    }
    
    reverse(ans.begin(),ans.end());    
    return ans;
}


int main()
{


    
        string s;
        int burstLen;

        cin >> s;
        cin >> burstLen;

        cout << solve(s,burstLen) << "\n";
}

解决方法

我尝试了一下,但是看起来很复杂,所以我建议使用标准库中的一些函数来简化函数。

示例:

#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <iterator>

std::string solve(const std::string& in,size_t burstlen) {
    std::string retval;

    for(std::string::const_iterator begin = in.cbegin(),bend;
        begin != in.end();
        begin = bend) 
    {

        // find the first char not equal to the current char
        bend = std::find_if_not(std::next(begin),in.end(),[curr=*begin](char ch){ return ch==curr; });

        if(std::distance(begin,bend) < burstlen) {
            // length ok,append it
            retval.append(begin,bend);
        }
    }

    return retval;
}

int main() {
    std::initializer_list<std::string> tests{
        "abbccccdd","abbcccdeaffff"};
    for(auto test : tests) std::cout << solve(test,3) << '\n';
}

输出:

abbdd
abbdea
,

至少最好使用容器适配器std::queue而不是std::stack,因为不需要调用算法std::reverse

此外,如果堆栈中的项目包含第二个存储频率的数据成员,那么您只需增加此数据成员的重复字符即可,而不是将每个重复的字符放在堆栈中。

例如您程序中的此代码段

    if (!ms.empty() && ms.top().first == s[i])
    {
        int count = ms.top().second;
        ms.push({s[i],count + 1});
    }

使函数定义过于复杂和不清楚,因为相同的字符以不同的频率被压入堆栈。

但是,如果要使用容器适配器std :: stack,则函数定义可能看起来更简单。您没有使用std::string类的功能。

这里是一个演示程序,展示了如何使用您的方法std::stack来编写函数。

#include <iostream>
#include <string>
#include <utility>
#include <stack>
#include <iterator>
#include <algorithm>

std::string solve( const std::string &s,size_t burstLen )
{
    std::stack<std::pair<char,size_t>> stack;
    
    for ( const auto &c : s )
    {
        if ( stack.empty() || stack.top().first != c )
        {
            stack.push( { c,1 } );
        }
        else
        {
            ++stack.top().second;
        }
    }

    std::string ans;
    
    while ( !stack.empty() )
    {
        if ( stack.top().second < burstLen )
        {
            ans.append( stack.top().second,stack.top().first );
        }
        stack.pop();
    }
    
    std::reverse( std::begin( ans ),std::end( ans ) );
    
    return ans;
}

int main()
{
    std::cout << solve( "abbccccdd",3 ) << '\n';
    std::cout << solve( "abbcccdeaffff",3 ) << '\n';
}

程序输出为

abbdd
abbdea

在删除一个不小于突发长度的字符序列后,从堆栈的左侧和右侧子序列中得到一个新的序列,该序列又一次不小于突发长度,并且还需要删除它。

在这种情况下,您可以使用两个堆栈。

这是一个演示程序。

#include <iostream>
#include <string>
#include <utility>
#include <stack>
#include <iterator>
#include <algorithm>

std::string solve( const std::string &s,size_t>> stack_in;
    
    for ( const auto &c : s )
    {
        if ( stack_in.empty() || stack_in.top().first != c )
        {
            stack_in.push( { c,1 } );
        }
        else
        {
            ++stack_in.top().second;
        }
    }

    std::stack<std::pair<char,size_t>> stack_out;

    while ( !stack_in.empty() )
    {
        if ( !stack_out.empty() && stack_out.top().first == stack_in.top().first )
        {
            if ( stack_out.top().second + stack_in.top().second < burstLen )
            {
                stack_out.top().second += stack_in.top().second;
            }
            else
            {
                stack_out.pop();
            }
        }
        else if ( stack_in.top().second < burstLen )
        {
            stack_out.push( stack_in.top() );
        }
        
        stack_in.pop();
    }
    
    std::string ans;
    
    while ( !stack_out.empty() )
    {
        ans.append( stack_out.top().second,stack_out.top().first );
        stack_out.pop();
    }
    
    return ans;
}


int main()
{
    std::cout << solve( "abbccccdd",3 ) << '\n';
    std::cout << solve( "aabcddeeedccbaa",3 );
}

程序输出为

abbdd
abbdea
aabbaa
,

我的解决方法:

创建一个由字符和字符数组成的成对堆栈

如果堆栈为空或堆栈的顶部元素与字符串中的当前元素不相等

情况1:如果堆栈顶部元素的频率大于或等于k,则将其存储在一个变量中,例如count,弹出堆栈计数时间元素。

情况2:如果堆栈为空,则只需以频率1将元素推入堆栈。

遍历完整的字符串时,如果堆栈的顶部元素的频率大于突发频率,则开始从堆栈(计数)次中删除元素。

现在,我们在堆栈中保留了剩余的元素,开始弹出它们并将其存储在字符串中,然后反转字符串以保留顺序。

返回新字符串。

更新:已解决。在这种情况下缺少一行if(ms.empty()== true || ms.top()。first!= s [i])弹出元素后,我们还必须插入字符频率为1的当前元素。

#include<iostream>
#include<stack>
using namespace std;

string solve(string s,int burstLen)
{
    stack<pair<char,int>> ms;
    
    for (int i = 0; i < s.size(); i++)
    {
        if (!ms.empty() && ms.top().first == s[i])
        {
            int count = ms.top().second;
            ms.push({s[i],count + 1});
        }
        
        else
        {
            if(ms.empty() == true  ||  ms.top().first != s[i])
            {
                if(!ms.empty() && ms.top().second >= burstLen)
                {
                    int count = ms.top().second;
                    
                    while(!ms.empty() && count--)
                        ms.pop();
                        
                    ms.push({s[i],1});
                }
                
                else
                    ms.push({s[i],1});
            }
        }

    }
    
    if(!ms.empty() and ms.top().second >= burstLen)
    {
        int count = ms.top().second;
        while(!ms.empty() && count--)
            ms.pop();
    }

    string ans = "";
    while (!ms.empty())
    {
        ans += ms.top().first;
        ms.pop();
    }
    
    reverse(ans.begin(),ans.end());    
    return ans;
}


int main()
{


    int t;
    cin >> t;
    
    while(t--)
    {
        string s;
        int burstLen;
        cin >> s >>burstLen;

        cout << solve(s,burstLen) << "\n";
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-