前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode程序员面试金典】面试题 01.06. Compress String LCCI

【LeetCode程序员面试金典】面试题 01.06. Compress String LCCI

作者头像
韩旭051
发布2020-06-22 17:12:17
3040
发布2020-06-22 17:12:17
举报
文章被收录于专栏:刷题笔记刷题笔记

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

Example 1:

Input: "aabcccccaaa" Output: "a2b1c5a3" Example 2:

Input: "abbccd" Output: "abbccd" Explanation: The compressed string is "a1b2c2d1", which is longer than the original string.

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/compress-string-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

JAVA 字符串 直接 用串感觉内存一定爆炸

所以要用字符数组 StringBuilder

双指针判断

代码语言:javascript
复制
class Solution {
    public String compressString(String S) {
    int N = S.length();
    int i = 0;
    StringBuilder sb = new StringBuilder();
    while (i < N) {
        int j = i;
        while (j < N && S.charAt(j) == S.charAt(i)) {
            j++;
        }
        sb.append(S.charAt(i));
        sb.append(j - i);
        i = j;
    }

    String res = sb.toString();
    if (res.length() < S.length()) {
        return res;
    } else {
        return S;
    }
}
}

在 C++ 中,res += s 和 res = res + s 的含义是不一样的。前者是直接在 res 后面添加字符串;后者是用一个临时对象计算 res + s,会消耗很多时间和内存

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • JAVA 字符串 直接 用串感觉内存一定爆炸
  • 所以要用字符数组 StringBuilder
  • 双指针判断
  • 在 C++ 中,res += s 和 res = res + s 的含义是不一样的。前者是直接在 res 后面添加字符串;后者是用一个临时对象计算 res + s,会消耗很多时间和内存
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档