当前位置:网站首页>String compression
String compression
2022-08-09 01:02:00 【Shen Yuequan】
字符串压缩
题目描述
字符串压缩.利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能.比如,字符串aabcccccaaa会变为a2b1c5a3.若“压缩”后的字符串没有变短,则返回原先的字符串.你可以假设字符串中只包含大小写英文字母(a至z).
代码实现
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string compressString(string S) {
char curChar = S[0];
int cnt = 1;
string ans;
for (int i = 0; i < S.length(); i++) {
if (curChar == S[i + 1]) {
cnt++;
}
else {
ans += curChar + to_string(cnt);
curChar = S[i + 1];
cnt = 1;
}
}
int a1 = ans.length();
int a2 = S.length();
if (ans.length() >= S.length()) {
return S;
}
return ans;
//return ans.length() < S.length() ? ans : S;
}
};
int main()
{
Solution sol;
cout << sol.compressString("aabbbcc") << endl;
}
边栏推荐
- 【元胞自动机】基于元胞自动机模拟社会力因素下的灾害人员疏散应急仿真附matlab代码
- “圆梦杯”大学生智能硬件设计大赛 初赛样题——理论题作答
- jetson nano 开机闪一下然后黑屏
- node工具之nodemon
- 5-3 Seaborn 分布绘图
- Use Ehcache distributed cache to easily create commercial-grade high-concurrency, high-performance API interfaces!
- ABAP 报表中如何以二进制方式上传本地文件
- LeetCode精选200道--双指针篇
- 【学习-目标检测】目标检测之——YOLO v3
- 轻量级网络ESPNet系列 空洞卷积简介
猜你喜欢
【科研-学习-pytorch】5-boardcasting、合并分割
clickhouse 思维导图
数学建模美赛题型分类
【学习-目标检测】目标检测之—FPN+Cascade+Libra
在Ubuntu/Linux环境下使用MySQL:解决com.mysql.jdbc.PacketTooBigException: Packet for query is too large的问题
图像去雾概述
Use Ehcache distributed cache to easily create commercial-grade high-concurrency, high-performance API interfaces!
「复盘」面试 BAMT 回来整理 398 道高频面试题,助你拿高薪 offer
Unity3D小白学习日记(02):U3D如何连接SQL SERVER数据库(亲测可行!)
控件限制总结
随机推荐
微信企业号开发之开启回调模式
4-5 Matplotlib库 散点图
软考总结博客
等到中心化的平台不再,衍生于这个平台的一切都将化作泡影
Sencha touch中Ext.data.Store获取json串中key值的方法
Discourse 的关闭主题(Close Topic )和重新开放主题
5-2 Seaborn 分类绘图
低代码接口开发平台——YesApi(API+数据表单)
笔记| 矩阵分析中需要复习的线性代数知识
JSON basics, transfer JSON data, and introduce four mainstream frameworks, jackson, gson, fastjson, and json-lib!
笔记&代码 | 统计学——基于R(第四版) 第四章随机变量的概率分布
CondConv--动态卷积思想
NodeJs连接mysql数据库
Unity3D小白学习日记(03):Unity3D 常用技巧整理(大量干货!)
Sencha Touch延迟加载模块中的小类提高程序进入每个模块时性能
轻量级网络ESPNet系列 空洞卷积简介
requestAnimationFrame实现浏览器动画
理财产品募集期和开放期有什么区别?
灰色预测模型
Early departure, learning source half a year, finally got the ants Offer to share the interview process