当前位置:网站首页>面试题 01.06. 字符串压缩
面试题 01.06. 字符串压缩
2022-07-27 23:29:00 【欢迎来到对抗路】
题目要求
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
输入:"aabcccccaaa"
输出:"a2b1c5a3"
示例2:
输入:"abbccd"
输出:"abbccd"
解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
提示:
字符串长度在[0, 50000]范围内
class Solution {
public:
string compressString(string S) {
int len = S.size();
string s1;
int count = 0;
for(int i = 0; i < len; i++)//遍历字符串
{
count++;//用于记录字母的次数
if(S[i] != S[i+1])//若当前字母和下一个字母不同,则将该字母以及该字母次数存储在s1中
{
s1+=S[i];
s1 += to_string(count);
count = 0;
}
}
if(len > s1.size())
return s1;
else
return S;
}
};
心得体会
to_string(2),将数字转换为字符的形式
边栏推荐
- Centralized management of clusters
- LeetCode 2351. 第一个出现两次的字母
- Unity Shader入门精要学习——基础纹理
- Huawei's Hubble investment shares in VCSEL chip manufacturer Zonghui Xinguang
- 糟糕程序员的20个坏习惯
- System clock failure of database fault tolerance
- Basic concept and classification of i/o equipment
- ABAP CDS Table Function介绍与示例
- EWM收货ECC交货单校验逻辑问题
- The total investment is nearly 1.6 billion yuan! Qianzhao optoelectronics VCSEL and high-end LED chip projects officially started
猜你喜欢

开发 Flutter 录音功能的插件

现货白银如何计算盈亏

Learn how Baidu PaddlePaddle easydl realizes automatic animal recognition in aquarium

Transplant QT system for i.mx6ull development board - cross compile QT code

Principle of logistic regression

Shutter -- password login registration interface

《安富莱嵌入式周报》第275期:2022.07.18--2022.07.24

测试人员需要了解的软件流程

Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始

Three instance
随机推荐
3000 words and 11 pictures hard core popular science: what is edge computing? What are the connections and differences with cloud computing?
Xinyi information technology, a domestic NB IOT chip manufacturer, received 200million yuan of a+ round financing
Arm中国夺权大战的背后:“独立”两年,仍难“自主”?
晶方科技:光刻机厂商ASML为公司参与并购的Anteryon公司的最主要客户之一
Wu xiongang sent an internal letter: arm's allegations are unwarranted, and no damage is allowed to the existing achievements!
Flutter--密码登录注册界面
比亚迪半导体完成8亿元A+轮融资:30家知名投资机构入局,估值已达102亿元!
氧气温湿度模组
4月全球智能手机出货同比下滑41%,华为首次超三星成全球第一
华为回应美国封锁供应链:他们仍需为5G专利付费
Count the number of given strings in a string
JG-数据重置(wd)
Lua进阶
ICML2022 | 在线决策Transformer
8000字讲透OBSA原理与应用实践
Fluent call interface UI
Standing at the crossroads of digital retail transformation, we need to look at it from a new perspective
Huawei responded to the US blockade of the supply chain: they still have to pay for 5g patents
Cesium add inundation analysis measurement area
实现ABCD字母递增