题解 | #压缩字符串(一)#

压缩字符串(一)

http://www.nowcoder.com/practice/c43a0d72d29941c1b65c857d8ac9047e

import java.util.*;


public class Solution {

    public String compressString (String param) {
// write code here
        char []str=param.toCharArray();
      //保存结果
        StringBuffer res=new StringBuffer();
        if(str.length==0)return res.toString();
        res.append(str[0]);
        int count=1;//记录字母数
        for(int i=1;i<str.length;i++){
            if(str[i]==str[i-1]){
                count++;
            }else{
                if(count!=1){
                    res.append(count);
                    count=1;
                    res.append(str[i]);
                }else{
                    res.append(str[i]);
                }
            }
        }
      //如果最后不是1,拼接上
        if(count!=1){
             res.append(count);
        }
        
        return res.toString();
        
    }
}
全部评论

相关推荐

06-12 10:50
门头沟学院 Java
你的不定积分没加C:我怎么在学院群看到了同样的话
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务