String Compress


Description:

Compress string

Example:

"aabbaaaccd" -> "a1b1a2c2d"
"ababde"  ->  "ababde"

Idea:

跟count and say类似,自己写findNextChar函数。

Code:

#include <iostream>
using namespace std;

int findNextChar(string input, int i){
    int j=i+1;
    while(j<input.size() && input[j]==input[i]){
        j++;
    }
    return j;
}

string compressString(string input){
    string result;
    int i=0;
    while(i<input.size()){
        int j=findNextChar(input, i);
        if(j-i==1) result = result + input[i];
        else{
            result = result + input[i];
            result += to_string(j-i-1);
        }
        i=j;
    }
    return result;
}


int main(){
    string input="aaabbabbcc";
    // string input="";
    string result=compressString(input);
    cout<<result<<endl;
}

results matching ""

    No results matching ""