首页 > 其他分享 >一道笔试题:给定编码规则,实现decode()方法

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

时间:2022-10-20 18:22:26浏览次数:53  
标签:字符 ch oldStr 笔试 pub decode 给定 str sb

一道笔试题:给定编码规则,实现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);
    }
}

http://t.zoukankan.com/fengzhblog-p-3222621.html

标签:字符,ch,oldStr,笔试,pub,decode,给定,str,sb
From: https://www.cnblogs.com/sunny3158/p/16810818.html

相关文章