#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
/*
问题:利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。
比如,字符串aabcccccaaa会变为a2b1c5a3.若“压缩”后的字符串没有变短,
则返回原先的字符串。
分析:本质上就是寻找相邻相同字母的问题。当相邻两个字符不同时,开始重新计数
从后向前,
暴力破解来做
输入:
aabcccccaaa
m
ma
mm
输出:
a2b1c5a3
m
ma
mm
关键:
1 本质前后寻找一段连续相同字母的首标和末标,注意对最后一段相同字母处理
*/
string stringCompress(const string& str)
{
if(str.empty())
{
return str;
}
int length = str.length();
stringstream sResult;
//只有一个字符,直接返回该字符串
if(length == 1)
{
return str;
}
int begin = 0;
int end = begin + 1;
while(end < length)
{
//如果前后相邻部分相同,继续寻找下标
if( str[begin] == str[end] )
{
end++;
continue;
}
//如果前后相邻部分不同,则需要,设定当前字符的截止下标为end-1,并重新设置下一处字符起始下标为end
else
{
end = end - 1;
int iLen = end - begin + 1;
sResult << str[begin] << iLen;
begin = end + 1;
end = begin + 1;
}
}
//对最后一个end进行处理
end = end - 1;
int iLen = end - begin + 1;
sResult << str[begin] << iLen;
if(sResult.str().length() < str.length())
{
return sResult.str();
}
else
{
return str;
}
}
int main(int argc,char* argv[])
{
string str;
while(cin >> str)
{
string sResult = stringCompress(str);
cout << sResult << endl;
}
system("pause");
return 0;
}
程序员面试金典: 9.1数组与字符串 5字符串压缩
最新推荐文章于 2016-12-20 15:26:44 发布