Monday, July 26, 2021

Algoexpert Caesar Cipher Encryptor.java

import java.util.*;
class Program {
// O(n) T | O(n) S
public static String caesarCypherEncryptor(String str, int key) {
// handle corner cases
if (str == null || str.length() == 0) {
return str;
}
int n = str.length();
char[] encoded = new char[n];
for (int i = 0; i < n; i++) {
encoded[i] = getNewChar(str.charAt(i), key);
}
return new String(encoded);
}
private static char getNewChar(char oldChar, int key) {
return (char)('a' + (oldChar - 'a' + key) % 26);
}
}

No comments:

Post a Comment