来自X公司的实习生面试题,即给定一个string s = “abcabcabcbcc”,return “3a4b5c”;
class Solution {
public:
string stringCount(string s)
{
map<char, int> mp;
map<char, int> :: iterator it;
for (int i = 0; i < s.size(); ++i) {
mp[s[i]] ++;
}
string ret;
for (it = mp.begin(); it != mp.end(); ++it) {
if (it -> second > 0) {
char count = it -> second + '0';
ret.push_back(count);
ret.push_back(it->first);
}
}
return ret;
}
};
class Solution {
public:
string stringCompress(string s)
{
string ret;
int count = 1;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == s[i-1]) {
count ++;
if (i == s.size()-1) {
ret += (count + '0');
ret += s[i];
}
}
else {
ret += (count+ '0');
ret += s[i-1];
count = 1;
}
}
return ret;
}
};