字符串的压缩(面试题)

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

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;i1;i=pos+1){
            temp = chs[i];
            pos = i;
            count = 1;
            while(pos1 && 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);
    }
}

你可能感兴趣的:(笔试编程题)