zoj 1006 Java

来源:互联网 发布:php注册登录系统源码 编辑:程序博客网 时间:2024/04/30 05:20

自己的想法是按照基本数学公式一步步算出来的笨方法,想着必然有精简的方法,百度一下果然涨姿势了,学好数学果然很重要啊

/*
 * 功能:zoj1006 字符串编码、解码
 * 说明:如果 a=(b-i)mod28那么 b=(a+i)mod28,这个等式对于任意数当然是不成立的,
 * 但是当像题目所说那样,a,b属于[0,27]且XmodY的结果始终为正的情况下是没问题的,
 * 所以在反推的时候直接这样就可以了。
 * 时间:2014.12.20
 */
import java.util.*;


public class Main {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myScanner = new Scanner(System.in);
int k;
while((k = myScanner.nextInt()) !=0){
String cipher = myScanner.next();
Decryption mySolutiong = new Decryption(k, cipher);
String result = mySolutiong.getResult();
System.out.println(result);
}
myScanner.close();
}


/*
* 功能:zoj 1006
*/
static class Decryption{
int kInt;
String ciphertext;
public Decryption(int k, String cipher) {
// TODO Auto-generated constructor stub
kInt = k;
ciphertext = cipher;
}
/*
* zoj 1006解决方案
*/
public String getResult(){
return getMessage(cipherToInt());
}
/*
* 功能:将密文转换为数字编码
*/
int[] cipherToInt(){
char[] tmp = ciphertext.toCharArray();
int len = tmp.length;
int[] cipherCode = new int[len];

for(int i=0; i<len; ++i){
if(tmp[i] == '_')
cipherCode[i] = 0;
else if(tmp[i] == '.')
cipherCode[i] = 27;
else if(tmp[i] >= 'a' && tmp[i] <= 'z') {
cipherCode[i] = tmp[i] - 'a' + 1;
}
}
return cipherCode;
}
/*
* 功能:将密文数字编码转换为原文
*/
String getMessage(int[] cipherCode){
int len = cipherCode.length;
int[] messageCode = new int[len];
int[] tmpMessageCode = new int[len];
String message = "";
for(int i=0; i< cipherCode.length; ++i){
tmpMessageCode[i] = cipherCode[i] + i;
tmpMessageCode[i] %= 28;
messageCode[i*kInt%len] = tmpMessageCode[i];
}
for(int i=0; i<len; ++i){
if(messageCode[i] == 0)
message += "_";
else if(messageCode[i] == 27)
message += ".";
else if(messageCode[i]>0 && messageCode[i]<27) {
message += (char)('a' + messageCode[i] - 1);
}
}
return message;
}
}
}

0 0
原创粉丝点击