Thuật toán xoá ký tự lặp lại trong xâu bị sai

#include <iostream>
#include <string>

using namespace std;

void chuanhoa(string &s)
{
    for(int i=0;i<s.size();i++)
    {
        if('A' <= s.at(i) <= 'Z')
        {
            s.at(i) = tolower(s.at(i));
        }
    }
}

void res(string &s)
{
    if(s.size() < 1 ) return;
    for(int i=0;i<s.size()-1;i++)
    {
        for(int j=i+1;j<s.size();)
        {
            if(s.at(i) == s.at(j))
            {
                s.erase(j);
                continue;
            }
            break;
        }
    }
    return;
}

int main()
{
    string s = "hhhhoc hhhannnnh";
    //getline(cin, s);

    chuanhoa(s);
    res(s);
    cout << s;

}

out: h

mình mò mãi mà nó k biết sai đâu nữa

Cuối cùng là sai thế nào?

quên mất: đề là xóa ký tự repeated, vd: hddddd abbbb -> hd ab

:frowning:

1 Like
void chuanhoa(string &s)
{
    string output = "";
    for (int i = 0; i < s.length(); i++)
        if ('A' <= s[i] && s[i] <= 'Z')//Trong C++ không có so sánh 3 pha
            output += tolower(s[i]);
        else
            output += s[i];

    s = output;
}

void res(string &s)
{
    if (s.length() < 1) return;
    string output = "";
    for (int i = 0; i < s.length() - 1; i++)
        if (s[i] != s[i + 1])
            output += s[i];

    output += s[s.length() - 1];

    s = output;
}
1 Like

sau một thời gian ức chế thì mình đã fix được:frowning:

#include <iostream>
#include <string>

using namespace std;

void chuanhoa(string &s)
{
    for(int i=0;i<s.size();i++)
    {
        if('A' <= s.at(i) <= 'Z')
        {
            s.at(i) = tolower(s.at(i));
        }
    }
}

void res(string &s)
{
    if(s.size() < 1 ) return;
    for(int i=0;i<s.size()-1;i++)
    {
        for(int j=i+1;j<s.size();)
        {
            if(s.at(i) == s.at(j))
            {
                s.erase(j,1);
                continue;
            }
            break;
        }
    }
    return;
}

int main()
{
    // hhhhhhhhocccccc lLlLlLaap triinh vui laMmMm
    string s;
    getline(cin, s);

    chuanhoa(s);
    res(s);
    cout << s;

}

1 Like

Chỉ thêm s.erase(j,1); :smiling_imp:

Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos.
Notice that the default argument erases all characters in the string (like member function clear).

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?