基本字符串压缩
来源:互联网 发布:淘宝上靠谱的法国代购 编辑:程序博客网 时间:2024/06/18 10:57
利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。
给定一个string iniString为待压缩的串(长度小于等于3000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。
测试样例
“aabcccccaaa”
返回:”a2b…
class Zipper {public: //VC++测试结果正确! int power(int sum, int n){ int temp=sum; if(n==0) return 1; else if(n==1) return sum; else{ for(int i=1;i<n;i++) sum*=temp; return sum; } } string zipString(string iniString) { // write code here string result;//保持结果的字符串 result.clear(); int i; int count=0; int len=iniString.size(); char t;//指示结果字符串中的当前字符 t=iniString[0]; for(i=0;i<=len;i++){//用len取“=”号的原因,字符串iniString结束时 iniString[len+1]='\0',与其它字符不等, //故而可以进入随后的if语句进行count统计;如果len没有取"="将导致最后一个字符的统计数不能输出 if(t!=iniString[i]){ result+=t; if(count>9){//当count不止一位数时,进行处理 int temp=count; int tn=1; int j; while(temp>=10){//计算count的位数 temp=temp/10; tn++; } for(j=tn-1;j>=0;j--){//从最高位开始,将各位数字依次加入result中 result+=count/(power(10,j))+'0'; count=count%(power(10,j)); } //lenResult=lenResult+tn; }else{ result+=count+'0'; } count=1; t=iniString[i]; }else{ count++; } } if(result.size()<iniString.size()){ return result; }else{ return iniString; } }};
0 0
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 牛客网 | 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩
- 基本字符串压缩(Java)
- 空格替换2
- 微信开发中不出现“该公众号无法提供服务”
- UIWebView的用法
- 程序员将是人类最后一个被人工智能代替的工作
- sort命令详解
- 基本字符串压缩
- UIView
- 计算机网络-TCP协议三次握手过程分析
- 网站优化技巧
- Kindeditor编辑器的工具栏items的去和留
- springMvc 之 【javaBean读取属性配置文件中的值】---非注解方式
- 2015年8月9日11:01:08
- 初入SVM学习报告
- 用数组 和 链表 构建栈