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

压缩字符串(一)

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param param string字符串 
     * @return string字符串
     */
    public String compressString (String param) {
        // write code here
        if(param.length() == 0){
            return "";
        }
        char[] c = param.toCharArray();
        int count = 1;
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < c.length - 1;i++){
            if(c[i] == c[i+1]){
                count++;
            }else{
                sb.append(c[i]);
                if(count > 1){
                    sb.append(count);
                }
                count = 1;
            }
        }
        sb.append(c[c.length - 1]);
        if(count > 1){
            sb.append(count);
        }
        return sb.toString();
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务