/**
*
* 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 TestStringEncodeDemo {
public static String pub = "";
public static void decode(String str) {
/*
* 第一次操作判斷‘_’,以后所有的操作都是在遞歸后的字符串
*/
if (str.charAt(0) == '_') {
pub = pub + "/UL" + "_";
} else if ("123456789".indexOf(str.charAt(0)) == -1) {// 判斷是否是數值型的字符
pub += str.charAt(0) + "_";
} else if (str.length() == 1) {// 如果字符串只有一位跳出方法
pub += str;
return;
} else {
/*
* "123456789".indexOf(str.charAt(0))+1
* 通過這種方法能夠得到字符下標就是字符的值(因為是從0位開始的所有加1) 需求去的是字面值加1所有直接+2
*/
for (int i = 0; i < "123456789".indexOf(str.charAt(0)) + 2; i++) {
pub += str.charAt(1);// 取的是當前字符串的后一位
}
pub = pub + "_";
}
//遞歸截取字符串(代替了循環執行字符串的操作并且把判斷字符是否是int的值操作提取了)
if (str.length() != 1) {
TestStringEncodeDemo.decode(str.substring(1));
}
}
public static void encode(String str) {
String pub = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '_') { // 若以知字符串中包含有下劃線'_',則變換為用"/UL"
pub += "/UL";
} else if ("123456789".indexOf(str.charAt(i), 0) == -1) {// 字符串的當前字符不是大于0的數字字符,復制該字符與新字符串中
pub += str.charAt(i);
// 拼接最后一位
} else if ("0123456789".indexOf(str.charAt(i), 0) != -1 && i == (str.length() - 1)) {
pub += str.charAt(i);
}
// 字符串的當前字符是一個大于0的數字字符,并且還有后繼字符,
else if ("0123456789".indexOf(str.charAt(i), 0) != -1 && i != str.length() - 1) {
int pool = Integer.parseInt(str.charAt(i) + "");
for (int j = 0; j <= pool; j++) {
pub += str.charAt(i + 1);
}
}
pub += "_";
}
pub = pub.substring(0, pub.length() - 1);
System.out.println(pub);
}
public static void main(String[] args) {
// char c = "12345678".charAt(0);
// System.out.println(Character.getNumericValue(c) + 2);
// System.out.println("12345678".charAt(0));
String str = "24ab_2tt";
decode(str);
System.out.println(pub);
encode(str);
}
}