如何压缩字符串。例如:aaabbbccc - > A3B3C3

时间:2017-09-02 00:20:55

标签: c++ string algorithm run-length-encoding

我有一个函数,它接受一个小写字母(a-z)字符串,如果压缩字符串的长度不小于原始字符串,则返回一个压缩字符串或原始字符串。例如:aaabbbccc - > a3b3c3,abejd - > abejd

我无法将整数值放在我的char数组中。

特别是我的功能中的这一行:

newWord [k] = count;

如何将整数转换为字符,以便函数返回正确的字符串?

string compressString() {
int count;
int j;
char intString[32];
unsigned int k = 0;
string word;

cout << "Enter string to compress: ";
getline(cin, word);

char* newWord = new char[word.length() + 1];
for (unsigned int i = 0; i < word.length(); i++){
    count = 1;
    newWord[k] = word[i];
    k++;
    j = i;
    while (word[j + 1] == word[i]) {
        j++;
        count++;
        i = j;
    }
    if (k > word.length() - 1) {
        return word;
    }
    newWord[k] = count;
    k++;
}
string str(newWord);
delete[] newWord;
return str;
}

int main()
{
int response;
cout << "Enter test case "        << endl << endl;
cout << "0: Sort"                         << endl;
cout << "1: Get Permutations"             << endl;
cout << "2: Check Permutations"           << endl;
cout << "3: Check Permutation Palindrome" << endl;
cout << "4: Check Edits"                  << endl;
cout << "5: Compress String"              << endl << endl;
cout << "Selection: ";

cin >> response;
cin.ignore(1000, '\n');

while (response != 0) {
    switch (response) {
    case 0:
        mergeCase();
        break;
    case 1:
        permutationCase();
        break;
    case 2:
        checkPermutation();
        break;
    case 3:
        checkPalindrome();
        break;
    case 4:
        cout << checkEdits();
        break;
    case 5:
        cout << compressString();
        break;
    }
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

std::string compress_string(const std::string& s)
{
    std::string res;
    for (auto it = s.begin(); it != s.end(); ) {
        const auto next = std::find_if(it + 1, s.end(), [&](char c) { return *it != c; });
        const auto count = next - it;
        res += *it;
        if (count != 1) {
            res += std::to_string(count);
        }
        it = next;
    }
    return res;    
}

Demo