Compress String

Given a string and compress it to certain format, if the new length of compressed string is longer then return the original string.

e.g: aabcccc -> a2b1c4  abbcd -> abbcd

Solution:

1. check if this string need to be compressed

2. if compressing needed, compress it to the compressed one:

  when s[i]!=s[i-1] update the result, and finally update the final one

Or you can do this two process at the same time:

1. declear a new_length variable and each time when s[i]!=s[i-1] new_length+=2 and also update the result

2. When new_length > length just return the original one.

 

How to choose from these two solution depends on if the rate of needing compression for the input sets.

Code:

public boolean needCompress(String str){
    if(str.length()==0)
        return false;
    int len = str.length(), new_len = 2;
    for(int i = 1; i < len; i++){
        if(str.charAt(i)!=str.charAt(i-1)){
            new_len+=2;
            if(new_len > len)
                return false;
        }
    }
    return true;
}

public String compressStr(String str){
    if(!needCompress(str))
        return str;
    StringBuilder sb = new StringBuilder();
    int temp = 1;
    for(int i = 1; i < str.length(); i++){
        if(str.charAt(i)!=str.charAt(i-1)){
            sb.append(str.charAt(i-1));
            sb.append(temp);
            temp=1;
        }else
            temp++;
    }
    sb.append(str.charAt(str.length()-1));
    sb.append(temp);
    return sb.toString();
}
View Code

 

posted @ 2017-06-16 04:10  小风约定  阅读(69)  评论(0)    收藏  举报