简体   繁体   English

删除相邻的重复项

[英]Remove adjacent duplicates

Expected output is "ca" but I'm getting "aca" .预期 output 是"ca"但我得到"aca" I have dry ran it, but do not understood why it is doing so.我已经干过它,但不明白它为什么这样做。 Please, can anyone help me in solving this?请问,谁能帮我解决这个问题?

#include<bits/stdc++.h>
using namespace std;
    
int main()
{
    string a = "abbaca";
    int i = 0;
    while(i < a.size()){
        if(a[i] == a[i+1]){
            a.erase(i, i+1);
            i = 0;
        }
        else{
            i++;
        }
    }
    cout << a;
    
    return 0;
}

a.erase(i, i+1) is wrong. a.erase(i, i+1)是错误的。

The string::erase() method takes a starting index and a count, not a pair of indexes denoting a range, as you are thinking. string::erase()方法需要一个起始索引和一个计数,而不是您所想的表示范围的一对索引。

When removing the duplicate b s, i is 1, and you erase i+1=2 chars, thus "abbaca" becomes "aaca" , which is correct.删除重复的b时, i为 1,并且您删除i+1=2字符,因此"abbaca"变为"aaca" ,这是正确的。 But then, the loop starts over, and when removing the duplicate a s, i is 0, so you erase i+1=1 char, thus "aaca" becomes "aca" , which is wrong.但是随后,循环重新开始,当删除重复a时, i为 0,因此您擦除i+1=1字符,因此"aaca"变为"aca" ,这是错误的。

You want to remove exact 2 chars each time, so use a.erase(i, 2) instead.您每次都想准确删除 2 个字符,因此请改用a.erase(i, 2)

Online Demo在线演示

The function 'erase()' erases a part of the string content, shortening the length of the string.The second parameter in the erase function is the count, it means how many characters you want it to remove. function 'erase()' 擦除部分字符串内容,缩短字符串的长度。擦除 function 中的第二个参数是计数,表示您希望它删除多少个字符。 If you want 'ca' as expected output you should mention 2 as count of characters to be removed.如果您希望 'ca' 符合预期 output 您应该提到 2 作为要删除的字符数。 In the first case it becomes 2 so bb is removed but for 'aa' the count becomes as 1 so 'aca' is the output.在第一种情况下,它变为 2,因此 bb 被删除,但对于“aa”,计数变为 1,因此“aca”是 output。

Below is the code for output 'ca', change this erase statement as shown:下面是 output 'ca' 的代码,更改此擦除语句如下所示:

    if(a[i]==a[i+1]){
        a.erase(i,2);
        i=0;
    }

keep the rest as same保持 rest 相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM