zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 01.06. 字符串压缩

    题目:

    https://leetcode-cn.com/problems/compress-string-lcci/

    字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

    示例1:

    输入:"aabcccccaaa"
    输出:"a2b1c5a3"
    示例2:

    输入:"abbccd"
    输出:"abbccd"
    解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
    提示:

    字符串长度在[0, 50000]范围内。

    分析:

    先得到压缩后的字符串,再比较长度返回短的即可。

    程序:

    class Solution {
        public String compressString(String S) {
            if(S.length() == 0)
                return S;
            int times = 0;
            StringBuilder str = new StringBuilder();
            char ch = S.charAt(0);
            for(int i = 0; i < S.length(); ++i){
                if(S.charAt(i) == ch){
                    times++;
                }else{
                    str.append(ch);
                    str.append(times);
                    times = 1;
                    ch = S.charAt(i);
                }
            }
            str.append(ch);
            str.append(times);
            String res = str.toString();
            return res.length() < S.length() ? res : S;
        }
    }
  • 相关阅读:
    秀秀我的PENTAX的手动标头
    软件测试工具
    071226 冷
    071228晴转雨
    长假计划
    Merry Christmas
    信宿事件
    並べ替えーーバブルソート等
    收藏
    实践浪漫
  • 原文地址:https://www.cnblogs.com/silentteller/p/12390139.html
Copyright © 2011-2022 走看看