Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * CC150 1.5 Compress String
- * @author: Scarlett Chen
- * @time: 12/20/2014 Sat 9:57 PM
- * 时空复杂度都是o(n)?如果n是字符串里的字符数的话
- * 思路是:
- * 遍历每个字符,是否与前一个一样,一样就把count+1.不一样就把该字符和它的count放到压缩后的字符串内。
- * 当newString长度大于originalString时,继续对比就没有意义了,直接返回原来的字符串。
- *
- *
- * 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.
- */
- public class CompressString {
- public String compress(String s) {
- int len = s.length();
- if (len<=2) return s;
- char[] ch = s.toCharArray();
- StringBuilder newString = new StringBuilder();
- char currentChar=' ';
- int currentCount = 0;
- for (int i=0; i<len; i++) {
- if (i>0 && ch[i]==ch[i-1]) {
- currentCount++;
- }
- else {
- if (i>0) {
- newString.append(currentChar);
- newString.append(currentCount);
- if (newString.length()>len) return s;
- }
- currentChar = ch[i];
- currentCount = 1;
- }
- }
- if (newString.length()>= len) return s;
- else return newString.toString();
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- CompressString cs = new CompressString();
- String s = "aabcccccaaa";
- System.out.println(s+"--->"+cs.compress(s));
- s = "aa";
- System.out.println(s+"--->"+cs.compress(s));
- s = "#";
- System.out.println(s+"--->"+cs.compress(s));
- s = "Jiali Chen";
- System.out.println(s+"--->"+cs.compress(s));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement