Compress the string 'aabcccccaaa' into 'a2b1c5a3' and determine if it can be made smaller? This is a question from LeetCode interview question 01.06: String Compression Explanation.
发布时间
阅读量:
阅读量

解题方法 : 双指针遍历
首先设定变量ch,使其获取字符串S中的首个字符,同时初始化计数器count的值为1。随后,将ch与S中后续的字符依次进行比对,若两者相同,则对count进行加1操作;若不一致,则创建一个StringBuilder对象ans,并通过其append方法依次添加当前字符ch及其对应的计数count。接着将当前字符重新赋给ch,并将计数器重置为1,继续执行循环操作。当整个循环过程结束后,需将最终的字符ch及其对应的计数值添加至ans中。最终返回ans与原字符串S长度之间的较小值。
代码实现
class Solution {
public String compressString(String S) {
if(S.length()==0){
return S;
}
StringBuilder ans=new StringBuilder();
char ch=S.charAt(0);
全部评论 (0)
还没有任何评论哟~
