设计一种方法,通过给重复字符计数来进行基本的字符串压缩。
例如,字符串 aabcccccaaa
可压缩为 a2b1c5a3
。而如果压缩后的字符数不小于原始的字符数,则返回原始的字符串。
可以假设字符串仅包括a-z的字母。
样例
str=aabcccccaaa
返回 a2b1c5a3
str=aabbcc
返回 aabbcc
str=aaaa
返回 a4
方案一:
string compress(string &str) {
// write your code here
int index;
int count=1;
string compressStr="";
int compressIndex=0;
if(str.size()==0)
return str;
for(index=0;index<str.size();index++)
{
if(1 == count)
{
compressStr+=str[index];
compressIndex++;
}
if(str[index]==str[index+1])
{
count++;
continue;
}
compressStr+=to_string(count);
compressIndex++;
count=1;
}
if(compressStr.size()>=str.size())
return str;
else
return compressStr;
}
方案二:
string compress(string &str) {
// write your code here
int index;
int count=1;
string compressStr="";
int compressIndex=0;
if(str.size()==0)
return str;
compressStr+=str[0];
for(index=1;index<str.size();index++)
{
if(str[index]!=str[index-1])
{
compressStr+=to_string(count)+str[index];
count=1;
continue;
}
count++;
}
compressStr+=to_string(count);
if(compressStr.size()>=str.size())
return str;
else
return compressStr;
}
PUBLIC:
string to_string(int n)
{
int a[30],cnt=0;
string s="";
while(n)
{
a[cnt++]=n%10;
n/=10;
}
for(int i=cnt-1;i>=0;i--)
{
s+=('0'+a[i]);
}
return s;
}
};