当前位置:网站首页>字符串压缩
字符串压缩
2022-08-09 00:48:00 【沈跃泉】
字符串压缩
题目描述
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串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;
}
边栏推荐
猜你喜欢
5-3 Seaborn 分布绘图
浅谈自定义应用层协议与UDP的报文结构和注意事项
JSON basics, transfer JSON data, and introduce four mainstream frameworks, jackson, gson, fastjson, and json-lib!
CondConv--动态卷积思想
一名双非程序媛面试蚂蚁、美团、携程等大厂拿 offer 分享面试过程
在特征通道提升网络性能 --SENet网络详解
轻量级网络SqueezeNet学习记录
利用Ehcache分布式缓存,轻松打造商业级高并发、高性能API接口!
年初离职,学习半年源码,终于拿到了蚂蚁 Offer,分享面试过程
容器运维平台的故障处理-1
随机推荐
Using MySQL in Ubuntu/Linux environment: Modify the database sql_mode to solve the "this is incompatible with sql_mode=only_full_group_by" problem
一名双非程序媛面试蚂蚁、美团、携程等大厂拿 offer 分享面试过程
安装wcf框架
网络宽度扩充--Inception v1-v4,xception变式学习记录
Phoenix的安装配置以及数据处理(详细步骤)
轻量级网络SqueezeNet学习记录
【学习-目标检测】目标检测之——YOLO v3
动态style定义背景渐变
STM32H750VBT6 Keil5 error :flash download failed cortex-M7
supervisor 安装、配置、常用命令
京东三面惨遭被虐,关于 redis,高并发,分布式,问懵了
在vscode中编辑、编译、下载Keil工程
node工具之nodemon
leetcode-45-跳跃游戏 II
"Replay" interview BAMT came back to sort out 398 high-frequency interview questions to help you get a high salary offer
基本控件属性
全新Swagger3.0教程,OAS3快速配置指南,实现API接口文档自动化!
学习思想的内容总结
图像去雾概述
神经网络基本原理