基本字符串压缩

题目描述

利用字符重复出现的次数,编写一个方法,实现基本的字符串压缩功能。比如,字符串“aabcccccaaa”经压缩会变成“a2b1c5a3”。若压缩后的字符串没有变短,则返回原先的字符串。

给定一个string iniString为待压缩的串(长度小于等于3000),保证串内字符均由大小写英文字母组成,返回一个string,为所求的压缩后或未变化的串。

测试样例
"aabcccccaaa"
返回:"a2b1c5a3"
 
"welcometonowcoderrrrr"
返回:"welcometonowcoderrrrr"

 1 import java.util.*;
 2 
 3 public class Zipper {
 4     
 5     //计算压缩后大小
 6     public int countCompression(String str)
 7     {
 8         if(str == null || str.isEmpty()) return 0;
 9         char last = str.charAt(0);
10         int count = 1;
11         int size = 0;
12         for(int i = 1 ; i < str.length() ;++i)
13         {
14             if(str.charAt(i) == last)
15             {
16                 ++ count;
17             }
18             else
19             {
20                 last = str.charAt(i);
21                 size += 1 + String.valueOf(count).length();
22                 count = 1;
23             }
24         }
25         return size + 1 + String.valueOf(count).length();
26     }
27     
28     public String zipString(String iniString) {
29         // write code here
30         int size =  countCompression(iniString);
31         if(size >= iniString.length()) return iniString;
32         StringBuffer mystr = new StringBuffer();
33         char last = iniString.charAt(0);
34         int count = 1;
35         for(int i = 1 ;i < iniString.length() ; ++i)
36         {
37             if(last == iniString.charAt(i))
38                 ++count ;
39             else
40             {
41                 mystr.append(last);
42                 mystr.append(count);
43                 last = iniString.charAt(i);
44                 count = 1;
45             }
46         }
47         mystr.append(last);
48         mystr.append(count);
49         return mystr.toString();
50     }
51 }
原文地址:https://www.cnblogs.com/xiaoyesoso/p/5333004.html