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
public class decode{ 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){ decode d = new decode(); d.decode("24ab_2t2"); System.out.println(d.pub); }}?自己写的encode如下:
public void encode(String str){ for(int i=0;i<str.length();i++){ if(str.charAt(i)=='_'){ pub += "\\UL"; }else if(("123456789").indexOf(str.charAt(i), 0)==-1){ pub += str.charAt(i); } else if((("0123456789").indexOf(str.charAt(i), 0)!=-1)&&(i == str.length()-1)){ pub += str.charAt(i); } else if(("0123456789").indexOf(str.charAt(i),0)!=-1&&i != str.length()-1){ int loop = Integer.parseInt(str.charAt(i)+"") ; for(int j = 0;j<=loop;j++){ pub += str.charAt(i+1); } } pub += "_"; } pub = pub.substring(0,pub.length()-1); System.out.println(pub); }?
转载自http://www.cnblogs.com/closeeyes/archive/2013/06/19/3144834.html