|
36 | 36 | * Выходные данные:
|
37 | 37 | * это яблоко красное
|
38 | 38 | * </pre>
|
| 39 | + * |
| 40 | + * @see <a href="https://youtu.be/pjQ9sYo5bVE">Video solution</a> |
39 | 41 | */
|
40 | 42 | public class CaesarCipher {
|
41 | 43 |
|
42 | 44 | // Русский алфавит
|
43 | 45 | private static final String ALPHABET = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
|
44 | 46 |
|
45 | 47 | public String encode(String text, int shift) {
|
46 |
| - var words = text.split(" "); |
47 |
| - return Arrays.stream(words) |
48 |
| - .map(word -> encodeWord(word, shift)) |
49 |
| - .collect(Collectors.joining(" ")); |
| 48 | + return encodeWordWithSpacesSupport(text, shift); |
50 | 49 | }
|
51 | 50 |
|
52 |
| - private String encodeWord(String text, int shift) { |
53 |
| - var chars = text.toCharArray(); |
54 |
| - for (var i = 0; i < chars.length; i++) { |
55 |
| - var targetIndex = ALPHABET.indexOf(chars[i]) + shift; |
56 |
| - targetIndex %= ALPHABET.length(); |
57 |
| - chars[i] = ALPHABET.charAt(targetIndex); |
58 |
| - } |
59 |
| - return new String(chars); |
| 51 | + public String decode(String text, int shift) { |
| 52 | + return encodeWordWithSpacesSupport(text, -shift); |
60 | 53 | }
|
61 | 54 |
|
62 |
| - public String decode(String encryptedText, int shift) { |
63 |
| - var words = encryptedText.split(" "); |
| 55 | + private String encodeWordWithSpacesSupport(String text, int shift) { |
| 56 | + var words = text.split(" "); |
64 | 57 | return Arrays.stream(words)
|
65 |
| - .map(word -> decodeWord(word, shift)) |
| 58 | + .map(word -> encodeWord(word, shift)) |
66 | 59 | .collect(Collectors.joining(" "));
|
67 | 60 | }
|
68 | 61 |
|
69 |
| - private String decodeWord(String encryptedText, int shift) { |
70 |
| - var chars = encryptedText.toCharArray(); |
| 62 | + private String encodeWord(String word, int shift) { |
| 63 | + var chars = word.toCharArray(); |
71 | 64 | for (var i = 0; i < chars.length; i++) {
|
72 |
| - var targetIndex = ALPHABET.indexOf(chars[i]) - shift + ALPHABET.length(); |
73 |
| - targetIndex %= ALPHABET.length(); |
74 |
| - chars[i] = ALPHABET.charAt(targetIndex); |
| 65 | + var index = ALPHABET.indexOf(chars[i]) + shift; |
| 66 | + while (index < 0) { |
| 67 | + index += ALPHABET.length(); |
| 68 | + } |
| 69 | + index %= ALPHABET.length(); |
| 70 | + chars[i] = ALPHABET.charAt(index); |
75 | 71 | }
|
76 | 72 | return new String(chars);
|
77 | 73 | }
|
|
0 commit comments