java编写encode方法和decode方法,机试题

请你用java,c,c++ 中任何一种语言实现两个函数encode()和decode(),分别实现对字符串的变换和复原。
  变换函数encode()顺序考察以知字符串的字符,按以下规则逐组生成新字符串:
  (1)若已知字符串的当前字符不是大于0的数字字符,则复制该字符与新字符串中;
  (2)若以已知字符串的当前字符是一个数字字符,且他之后没有后继字符,则简单地将它复制到新字符串中;
  (3)若以已知字符串的当前字符是一个大于0的数字字符,并且还有后继字符,设该数字字符的面值为n,
     则将它的后继字符(包括后继字符是一个数字字符) 重复复制n+1 次到新字符串中;
  (4)以上述一次变换为一组,在不同组之间另插入一个下划线'_'用于分隔;
  (5)若以知字符串中包含有下划线'_',则变换为用"/UL".
  
  例如:encode()函数对字符串24ab_2t2的变换结果为 444_aaaaa_a_b_/UL_ttt_t_2

 1 public class decode{
 2  public String pub = "";
 3  
 4  public void decode(String str){
 5   if(str.charAt(0) == '_'){
 6    pub = pub + "//UL";
 7   }else if("123456789".indexOf(str.charAt(0))==-1){
 8    pub = pub + str.charAt(0)+"_";
 9   }else if(str.length()==1){
10    pub = pub + str;
11    return;
12   }else{
13    for(int i=0;i<"123456789".indexOf(str.charAt(0))+2;i++)
14     pub = pub + str.charAt(1);
15    pub = pub + "_";
16   }
17   if(str.length() != 1)
18    this.decode(str.substring(1));
19  }
20  
21  public static void main(String[] args){
22   decode d = new decode();
23   d.decode("24ab_2t2");
24   System.out.println(d.pub);
25  }
26 }

 自己写的encode如下:

 1  public void encode(String str){
 2          for(int i=0;i<str.length();i++){
 3              if(str.charAt(i)=='_'){
 4                  pub += "\UL";
 5              }else if(("123456789").indexOf(str.charAt(i), 0)==-1){
 6                  pub += str.charAt(i);
 7              }
 8              else if((("0123456789").indexOf(str.charAt(i), 0)!=-1)&&(i == str.length()-1)){
 9                  pub += str.charAt(i);
10              }
11              else if(("0123456789").indexOf(str.charAt(i),0)!=-1&&i != str.length()-1){
12                  int loop = Integer.parseInt(str.charAt(i)+"") ;
13                  for(int j = 0;j<=loop;j++){
14                      pub += str.charAt(i+1);
15                  }
16              }
17              pub += "_";
18             
19          }
20          pub = pub.substring(0,pub.length()-1);
21          System.out.println(pub);
22      }

  

原文地址:https://www.cnblogs.com/closeeyes/p/3144834.html