字符串的压缩(面试题)

参加网龙笔试碰到的题目:

package com.util.algorithm;

public class ZipString {

    /** * @param args */
    public static void getZip(String str){
        int pos = 0, count;
        char[] chs = str.toCharArray();
        char temp;
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<chs.length-1;i=pos+1){
            temp = chs[i];
            pos = i;
            count = 1;
            while(pos<chs.length-1 && chs[pos]==chs[pos+1]){
                //这里的有点需要注意,pos一定不能超出长度,小心
                count++;
                pos++;
            }
            if(count>1){
                sb.append(count);
                sb.append(temp);
            }else{
                sb.append(temp);
            }
        }
        System.out.println(sb.toString());
    }
    public static void main(String[] args) {
        String s = "wwwabcss";
        getZip(s);
    }
}
    原文作者:lds_lsj
    原文地址: https://blog.csdn.net/lds_lsj/article/details/48752299
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞