Alg.11 Caesar Cipher Encryptor

From algoexpert.io

This is a easy string-related problem, given a string and a number k, we need to shift every character in the string k positions in the alphabet list.

Basically, we iterate this string, get each expecting character after we shift k positions. According to the ASCII code, assume current character’s ASCII is c, the transformed ASCII is c - ‘a’ + k, then we get the remainder, answer will be ‘a’ + (c - ‘a’ + k) % (‘z’ - ‘a’ + 1).

Here is the code implementation:

1
2
3
4
5
6
7
8
9
10
public static String caesarCypherEncryptor(String str, int key) {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int diff = str.charAt(i) - 'a' + key;
int trans = diff % ('z' - 'a' + 1);
char c = (char)(trans + 'a');
ans.append(c);
}
return ans.toString();
}

Time complexity: O(n); Space complexity: O(n)

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信