CC189 - 1.6

1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

string compress(string str){
    string res = "";
    int count = 0;
    for(int i=0;i<str.size();i++){
        count++;
        if(i+1>=str.size() || str[i+1]!=str[i]){
            res +=string(1, str[i])+to_string(count);
            count = 0;
        }
    }
    return res.size()<str.size() ? res : str;
}

https://onlinegdb.com/B175lqRsN

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/89883535
1.6