利用结构体和栈,将不同的字符压入栈中,如果字符相同则将结构体的sum+1,查找完成后将栈反转,同时输出栈中字符和大于一的情况。
#include <algorithm> #include <stack> #include <string> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param param string字符串 * @return string字符串 */ typedef struct character{ char ch; int sum; }; string compressString(string param) { // write code here stack<character> Char; stack<character> temp2; if(param.empty()) return param; for(int i = 0; i < param.length(); i++) { character temp; //要先判断Char栈是否为空 if(Char.empty() || param[i] != Char.top().ch) { temp.ch = param[i]; temp.sum = 1; Char.push(temp); }else { Char.top().sum++; } } string str; while (!Char.empty()) { temp2.push(Char.top()); Char.pop(); } while(!temp2.empty()) { character temp = temp2.top(); str += temp.ch; if(temp.sum > 1) { str += to_string(temp.sum); } temp2.pop(); } // reverse(str.begin(), str.end()); return str; } };