一道笔试题:给定编码规则,实现decode()方法

public class CodeDecode {
    /*变换函数encode()顺序考察已知字符串的字符,按以下规则逐组生成新字符串:
      (1)若已知字符串的当前字符不是大于0的数字字符,则复制该字符与新字符串中;
      (2)若以已知字符串的当前字符是一个数字字符,且他之后没有后继字符,则简单地将它复制到新字符串中;
      (3)若以已知字符串的当前字符是一个大于0的数字字符,并且还有后继字符,设该数字字符的面值为n,
         则将它的后继字符(包括后继字符是一个数字字符) 重复复制n+1 次到新字符串中;
      (4)以上述一次变换为一组,在不同组之间另插入一个下划线'_'用于分隔;
      (5)若已知字符串中包含有下划线'_',则变换为用"/UL".*/
    // by fengzh.
    public String decode2(String oldStr) {
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<oldStr.length();i++) {
            char ch = oldStr.charAt(i);
            if(Character.isDigit(ch)){
                if(ch=='0'){
                    sb.append(ch);
                } else {
                    if(i==oldStr.length()-1){
                        sb.append(ch);
                    } else {
                        int n = ch - '0';
                        char nextCh = oldStr.charAt(i+1);
                        for(int j=0;j<n+1;j++){
                            sb.append(nextCh);
                        }
                    }
                }
                if(i!=oldStr.length()-1){
                    sb.append('_');
                }
            } else if(ch=='_') {
                sb.append("/UL");
            } else {
                if(i!=oldStr.length()-1){
                    sb.append(ch);
                    sb.append('_');
                }
            }
        }
        return sb.toString();
    }

    public String pub = "";

    public void decode(String str) {
        if (str.charAt(0) == '_') {
            pub = pub + "//UL";
        } else if ("123456789".indexOf(str.charAt(0)) == -1) {
            pub = pub + str.charAt(0) + "_";
        } else if (str.length() == 1) {
            pub = pub + str;
            return;
        } else {
            for (int i = 0; i < "123456789".indexOf(str.charAt(0)) + 2; i++)
                pub = pub + str.charAt(1);
            pub = pub + "_";
        }
        if (str.length() != 1)
            this.decode(str.substring(1));
    }

    public static void main(String[] args) {
        CodeDecode d = new CodeDecode();
        String oldStr = "24ab_2t2";
        // d.decode("24ab_2t2"); // 结果:444_aaaaa_a_b_//ULttt_t_2
        d.pub = d.decode2(oldStr); // 结果:444_aaaaa_a_b_/ULttt_t_2
        System.out.println(d.pub);
    }
}

posted on 2013-07-29 11:43  勤修  阅读(547)  评论(0编辑  收藏  举报

导航