careercup-数组和字符串1.5

1.5 利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串”aabcccccaaa“会变成”a2b1c5a3“。若”压缩“后的字符串没有变短,则返回原先的字符串。

类似 leetcode中 解法:Count and say.

C++实现代码:

#include<iostream>
#include<string>
using namespace std;

string compress(string str)
{
    if(str.empty())
        return "";
    int i,j=0;
    int len=str.length();
    string res;
    char c;
    for(i=0;i<len;i++)
    {
        if(str[i]!=str[j])
        {
            c=i-j+'0';
            res+=str[j];
            res+=c;
            j=i;
        }
    }
    c=i-j+'0';
    res+=str[j];
    res+=c;
    if(res.length()==2*str.length())
        return str;
    return res;
}

int main()
{
    string str="abcd";
    cout<<compress(str)<<endl;
}

 

posted @ 2014-12-03 17:06  Jessica程序猿  阅读(149)  评论(0编辑  收藏  举报