(C++)压缩字符串

    技术2023-11-26  95

    #include <iostream> using namespace std; #include <string> class Solution { public: string compressString(string S) { //字符扫描 char temp = S[0]; //计数 int count = 1; //输出字符串 string out; //遍历整个字符串 for (int i = 0; i <= S.length(); ++i) { if (i == 0) { out += S[0]; continue; } if (S[i] == temp) { count++; } else { out += to_string(count); count = 1; temp = S[i]; out += temp; } } if (out.length() <= S.length()) { return out; } else { return S; } } }; //测试代码 int main() { Solution method; string str = "abbccd"; string out = method.compressString(str); cout << out << endl; system("pause"); }
    Processed: 0.010, SQL: 9