zoukankan      html  css  js  c++  java
  • Cracking the coding interview--Q1.5

    原文

    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.

    译文

    利用计算字符个数的方式实现一种基本的字符串压缩函数。例如字符串"aabcccccaaa"将变成"a2blc5a3"。如果经过压缩的字符串不比原来的字符串短的话,应该返回原字符串。

    解答

    没什么好说的,直接模拟题目的要求就行了。

    public class Main {
    
        public static String compression (String str) {
            StringBuilder sb = new StringBuilder();
            int ct, pt = 0;
            int len = str.length();
            while(pt < len) {
                char ch = str.charAt(pt);
                ct = 1;
                for(int i = pt + 1 ; i < len; i++) {
                    if(str.charAt(i) == ch)
                        ct++;
                    else
                        break;
                }
                sb.append(ch).append(ct);
                pt += ct;
            }
            String res = sb.toString();
            if(res.length() < len)
                return res;
            else
                return str;
        }
            
        public static void main(String args[]) {
            String s1 = "aabcccccaaa";
            String s2 = "aab";
            System.out.println(compression(s1));
            System.out.println(compression(s2));
        }
    }
  • 相关阅读:
    图的邻接链表实现(c)
    图的邻接矩阵实现(c)
    好文
    第13章 红黑树
    函数 setjmp, longjmp, sigsetjmp, siglongjmp
    域名解析
    wget www.baidu.com执行流程分析
    信号处理篇
    第11章 散列表
    第10章,基本数据结构(栈,队列)
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186337.html
Copyright © 2011-2022 走看看