Chapter 01 Question 05: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

//Return different string
{
public:
    string stringDuplicate (string& str) {
        if (str == "") {
            return str;
        }
        int count = 1;
        string result = string (1,str[0]);
        for (int i = 1; i < str.length(); i++) {
            if (str[i] == str[i-1]) {
                count++;
            } else {
                if (count > 1) {
                    result.append(to_string(count) + str[i]);
                    count = 0;
                } else {
                    result = result + str[i];
                }
            }

        }
        if (count > 1) {
            result.append(to_string(count));
        }
        return result;
    }



};

results matching ""

    No results matching ""