题解 | #压缩牛群编号#
压缩牛群编号
https://www.nowcoder.com/practice/db9dd240e5f54b6d8eeadfbd9b7f865f
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param chars char字符型vector * @return char字符型vector */ vector<char> compress(vector<char>& chars) { // write code here vector<char> ans; int len = chars.size(); if (len == 1) return chars; int i = 1; int left = 0; while ( i < len) { while (i < len && chars[i] == chars[i-1]) { i++; } if (i - left > 1) { ans.push_back(chars[i-1]); int total = i - left; vector<char> tmp; while (total) { tmp.push_back(total%10 + '0'); total /= 10; } for (int i = tmp.size()-1; i >= 0; i--) { ans.push_back(tmp[i]); } left = i; } else { if (chars[i] != chars[i-1] && i > left) { ans.push_back(chars[i-1]); left = i; } i++; //ans.push_back(chars[i]); } } if (chars[i] != chars[i-1] && i > left) { ans.push_back(chars[i-1]); left = i; } return ans; } };