当前位置:网站首页>LeetCode_2632_字符串压缩
LeetCode_2632_字符串压缩
2022-08-09 22:04:00 【Fitz1318】
题目链接
题目描述
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa
会变为a2b1c5a3
。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a
至z
)。
示例1:
输入:"aabcccccaaa"
输出:"a2b1c5a3"
示例2:
输入:"abbccd"
输出:"abbccd"
解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
提示:
- 字符串长度在
[0, 50000]
范围内。
解题思路
双指针法
- 令
left
和right
都初始化为0
,right
指针遍历字符串,直到访问到不同字符时停止,此时right - left
便是首个字符的连续出现次数,即可完成首个字符的压缩操作 - 接下来,从下个字符开始,重复以上操作,直到遍历完成即可
AC代码
class Solution {
public String compressString(String S) {
int left = 0;
int right = 0;
StringBuilder ans = new StringBuilder();
while (left < S.length()) {
while (right < S.length() && S.charAt(left) == S.charAt(right)) {
right++;
}
ans.append(S.charAt(left)).append(right - left);
left = right;
}
return ans.length() < S.length() ? ans.toString() : S;
}
}
边栏推荐
- Under the NVM node installation;The node environment variable configuration
- &&、||、&、|
- Presto Event Listener开发
- 关于ETL的两种架构(ETL架构和ELT架构)
- 工作经验-组件封装(拖拽排序组件)
- leetcode:331. 验证二叉树的前序序列化
- leetcode:321. 拼接最大数
- Rust 解引用
- R语言修改dataframe数据列的名称:使用dplyr包的rename函数修改列名、使用colnmaes函数修改列名、在数据筛选的时候重命名列名
- Arcgis工具箱无法使用,显示“XML包含错误“的解决方法
猜你喜欢
Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
一本通2074:【21CSPJ普及组】分糖果(candy)
Jinshanyun earthquake, the epicenter is in bytes?
Presto Event Listener开发
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
月薪5K的运维小白如何成为月薪5W的高级架构师?
js十五道面试题(含答案)
【微服务~Nacos】Nacos服务提供者和服务消费者
迁移学习 & 凯明初始化
随机推荐
【GORM】模型关系-HasMany关系
异常处理(try,catch,finally)
制定量化交易策略的基本步骤有哪些?
Qt 消息机制和事件
c:forEach varStatus属性
ArrayList 和 LinkedList 区别
EasyExcel使用
Linux 配置MySQL
leetcode 39. 组合总和(完全背包问题)
17-GuliMall 搭建虚拟域名访问环境
【微信小程序开发(八)】音频背景音乐播放问题汇总
This article lets you quickly understand implicit type conversion [integral promotion]!
Flutter 绘制美不胜收的光影流动效果
DXF笔记:文字对齐的研究
肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
关于ETL的两种架构(ETL架构和ELT架构)
shell学习
Liver all night to write a thirty thousand - word all the commands the SQL database, function, speaks clearly explain operators, content is rich, proposal collection + 3 even high praise!
华为鸿蒙3.0的野望:技术、应用、生态
B. Neighbor Grid