我制作了一个vigenere加密/解密程序,它看起来像我想的那样工作,但是在一个非常大的文本文件(500万个字符aprox)上运行我的加密/解密需要2-4分钟。我已经查看了我的代码,无法看出哪些操作可能会减慢它的速度。有人知道我怎么能加快速度吗?
代码:
public static String encrypt(String text, String key)
{
String cipherText = "";
text = text.toLowerCase();
for(int i = 0; i < text.length(); i++)
{
System.out.println("Count: "+ i); //I just put this in to check the
//loop wasn't doing anything unexpected
int keyIndex = key.charAt(i%key.length()) - 'a';
int textIndex = text.charAt(i) - 'a';
if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') { //check letter is in alphabet
int vigenere = ((textIndex + keyIndex) % 26) + 'a';
cipherText = cipherText + (char)vigenere;
} else
cipherText = cipherText + text.charAt(i);
}
}
return cipherText;
}在运行加密之前,我有一个使用Scanner将文本文件读取到字符串的方法。此字符串加上预定义的密钥用于创建加密文本。
谢谢。
答案
多亏了RC --这是我花时间串起来的。如果其他人对此感兴趣,这是我更新的代码,它现在运行得很快:
public static String encrypt(String text, String key)
{
StringBuilder cipher = new StringBuilder();
for(int i = 0; i < text.length(); i++)
{
int keyIndex = key.charAt(i%key.length()) - 'a';
int textIndex = text.charAt(i) - 'a';
if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') {
int vigenere = ((textIndex + keyIndex) % 26) + 'a';
cipher.append((char)vigenere);
} else {
cipher.append(text.charAt(i));
}
}
return cipher.toString();
}发布于 2013-10-26 13:21:05
追加到StringBuilder,而不是创建新的字符串实例。你想做一个
buffer.append((char)vigenere);而不是cipherText = cipherText + (char)vigenere;
发布于 2013-10-26 13:24:24
目前你正在做
for(int i = 0; i < text.length(); i++){
...
int keyIndex = key.charAt(i%key.length()) - 'a';
...
}您可以尝试将keyIndex的计算从for-loop中删除,并在预处理步骤中实现。例如,可以将keyIndex值/字符存储在单独的数组中,并访问原始循环中的数组内容。这将为您节省一些计算步骤。
https://stackoverflow.com/questions/19606829
复制相似问题