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      }

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM