|
| 1 | +/* |
| 2 | +Problem Name: Shift Cipher |
| 3 | +Language: C++ |
| 4 | +Description: |
| 5 | + Given N test cases. For each test case: |
| 6 | + - Read an integer k (the shift value). |
| 7 | + - Read a string t (the text). |
| 8 | + - If the word "the" appears as a separate word in t, shift letters backward by k. |
| 9 | + - Otherwise, shift letters forward by k. |
| 10 | + - Spaces and non-alphabetic characters remain unchanged. |
| 11 | +
|
| 12 | +Approach: |
| 13 | + - Iterate over each character. |
| 14 | + - Check if it is an alphabet; shift it accordingly using ASCII values. |
| 15 | + - Use modulo 26 arithmetic for wrap-around. |
| 16 | + - Before shifting, determine if the word "the" exists in the string. |
| 17 | +
|
| 18 | +Example Input: |
| 19 | +2 |
| 20 | +3 |
| 21 | +hello world |
| 22 | +1 |
| 23 | +the cat is here |
| 24 | +
|
| 25 | +Example Output: |
| 26 | +khoor zruog |
| 27 | +sfd bzs hr ifsf |
| 28 | +
|
| 29 | +Time Complexity: O(L) per test case (L = length of string) |
| 30 | +Space Complexity: O(L) |
| 31 | +*/ |
| 32 | + |
| 33 | +#include <bits/stdc++.h> |
| 34 | +using namespace std; |
| 35 | + |
| 36 | +// Function to perform the shift cipher |
| 37 | +string shiftCipher(const string &text, int k, int direction) { |
| 38 | + string result; |
| 39 | + result.reserve(text.size()); |
| 40 | + |
| 41 | + for (char c : text) { |
| 42 | + if (c == ' ') { |
| 43 | + result += ' '; |
| 44 | + } else if (isalpha(static_cast<unsigned char>(c))) { |
| 45 | + char base = isupper(static_cast<unsigned char>(c)) ? 'A' : 'a'; |
| 46 | + int shifted = ((c - base) + direction * k) % 26; |
| 47 | + if (shifted < 0) shifted += 26; // handle negative modulo |
| 48 | + result += static_cast<char>(shifted + base); |
| 49 | + } else { |
| 50 | + result += c; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | +} |
| 56 | + |
| 57 | +int main() { |
| 58 | + ios::sync_with_stdio(false); |
| 59 | + cin.tie(nullptr); |
| 60 | + |
| 61 | + int N; |
| 62 | + cin >> N; |
| 63 | + cin.ignore(); // consume newline |
| 64 | + |
| 65 | + for (int i = 0; i < N; ++i) { |
| 66 | + int k; |
| 67 | + cin >> k; |
| 68 | + cin.ignore(); |
| 69 | + |
| 70 | + string t; |
| 71 | + getline(cin, t); |
| 72 | + |
| 73 | + // Check if "the" appears as a word (case-insensitive) |
| 74 | + bool containsThe = false; |
| 75 | + string word; |
| 76 | + for (size_t j = 0; j <= t.size(); ++j) { |
| 77 | + if (j == t.size() || t[j] == ' ') { |
| 78 | + if (!word.empty() && word == "the") { |
| 79 | + containsThe = true; |
| 80 | + break; |
| 81 | + } |
| 82 | + word.clear(); |
| 83 | + } else { |
| 84 | + word += tolower(static_cast<unsigned char>(t[j])); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + // Direction: -1 if "the" found, +1 otherwise |
| 89 | + cout << shiftCipher(t, k, containsThe ? -1 : 1) << '\n'; |
| 90 | + } |
| 91 | + |
| 92 | + return 0; |
| 93 | +} |
0 commit comments