痛定思痛开始刷cc150 压缩数据,使用stringBuffer

来源:互联网 发布:数控系统模拟软件 编辑:程序博客网 时间:2024/06/09 21:49
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.



soln

package test;


public class JumpTwo {
 
    public static void main(String[] args) {
    
        String k = "aa";
      
        System.out.println(compress(k));


    }


    public static String compress(String s) {
        if(s.length()==0) return s;
        StringBuffer b= new StringBuffer();
        int cnt =1;
        
        for(int i=0;i<s.length();i++){
            if((i==s.length()-1)||s.charAt(i)!=s.charAt(i+1)){
                b.append(s.charAt(i));
                b.append(cnt);
                cnt=1;
            }
            else cnt++;
        }
         
        String s2  =b.toString();
        if(s2.length()>s.length()) {
            return s;
        }else return s2;


    }
}

0 0
原创粉丝点击