標籤:提取 取字串 dede val 沒有 test 規則 rgs 包括
/**
*
* 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);
}
}
Java decode機試題