Skip to content

Commit 6efedf6

Browse files
authored
Update MonoAlphabetic.java
1 parent d28faa2 commit 6efedf6

File tree

1 file changed

+6
-26
lines changed

1 file changed

+6
-26
lines changed

src/main/java/com/thealgorithms/ciphers/MonoAlphabetic.java

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,14 @@ private MonoAlphabetic() {
1010
// Encryption method
1111
public static String encrypt(String data, String key) {
1212
StringBuilder sb = new StringBuilder();
13-
14-
// Convert to uppercase to match the key mapping
1513
data = data.toUpperCase();
1614

1715
for (char c : data.toCharArray()) {
1816
if (c >= 'A' && c <= 'Z') {
19-
// Get the index (0-25) for the character
20-
int idx = c - 'A';
21-
// Append the character at the corresponding index in the key
22-
sb.append(key.charAt(idx));
17+
int idx = c - 'A'; // Index in alphabet
18+
sb.append(key.charAt(idx)); // Append the character from the key
2319
} else {
24-
// If character is not A-Z, append it as is
25-
sb.append(c);
20+
sb.append(c); // Append non-alphabet characters directly
2621
}
2722
}
2823
return sb.toString();
@@ -31,34 +26,19 @@ public static String encrypt(String data, String key) {
3126
// Decryption method
3227
public static String decrypt(String data, String key) {
3328
StringBuilder sb = new StringBuilder();
34-
35-
// Convert to uppercase to match the key mapping
3629
data = data.toUpperCase();
3730

3831
for (char c : data.toCharArray()) {
3932
if (c >= 'A' && c <= 'Z') {
40-
// Get the index from the key for the character
41-
int idx = getIndex(c, key);
42-
// Append the original character
33+
int idx = key.indexOf(c); // Get the index in the key
4334
if (idx != -1) {
44-
char originalChar = (char) (idx + 'A');
35+
char originalChar = (char) (idx + 'A'); // Convert index back to character
4536
sb.append(originalChar);
4637
}
4738
} else {
48-
// If character is not A-Z, append it as is
49-
sb.append(c);
39+
sb.append(c); // Append non-alphabet characters directly
5040
}
5141
}
5242
return sb.toString();
5343
}
54-
55-
// Helper method to get index of a character in the key
56-
private static int getIndex(char c, String key) {
57-
for (int i = 0; i < key.length(); i++) {
58-
if (key.charAt(i) == c) {
59-
return i; // Return the index if the character matches
60-
}
61-
}
62-
return -1; // Return -1 if character not found (should not happen for valid inputs)
63-
}
6444
}

0 commit comments

Comments
 (0)