@@ -10,19 +10,14 @@ private MonoAlphabetic() {
10
10
// Encryption method
11
11
public static String encrypt (String data , String key ) {
12
12
StringBuilder sb = new StringBuilder ();
13
-
14
- // Convert to uppercase to match the key mapping
15
13
data = data .toUpperCase ();
16
14
17
15
for (char c : data .toCharArray ()) {
18
16
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
23
19
} 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
26
21
}
27
22
}
28
23
return sb .toString ();
@@ -31,34 +26,19 @@ public static String encrypt(String data, String key) {
31
26
// Decryption method
32
27
public static String decrypt (String data , String key ) {
33
28
StringBuilder sb = new StringBuilder ();
34
-
35
- // Convert to uppercase to match the key mapping
36
29
data = data .toUpperCase ();
37
30
38
31
for (char c : data .toCharArray ()) {
39
32
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
43
34
if (idx != -1 ) {
44
- char originalChar = (char ) (idx + 'A' );
35
+ char originalChar = (char ) (idx + 'A' ); // Convert index back to character
45
36
sb .append (originalChar );
46
37
}
47
38
} 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
50
40
}
51
41
}
52
42
return sb .toString ();
53
43
}
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
- }
64
44
}
0 commit comments