Given a string s and an integer n, rearrange s into n rows so that s can be read vertically (top-down, left to right).
Constraints
Length of s ≤ 10000
n ≤ 1000
Example 1
Input
s = “abcdefghi”
n = 5
Output
1 ["af", "bg", "ch", "di", "e"]["af", "bg", "ch", "di", "e"]Explanation
This reads vertically as:
1 2 3 4 5 ["af", "bg", "ch", "di", "e"]["af", "bg", "ch", "di", "e"]
Simple Vertical Cipher in C++
We know the transformed result has n rows, thus we can allocate vector of N size. Then going through each character of the string, we append it to the corresponding row – which we can easily increment the row and remember to rewind to the first row by modulus operator ie. %.
1 2 3 4 5 6 7 8 9 | vector<string> verticalCipher(string s, int n) { vector<string> ans(n, ""); int r = 0; for (auto &c: s) { ans[r].push_back(c); r = (r + 1) % n; } return ans; } |
vector<string> verticalCipher(string s, int n) { vector<string> ans(n, ""); int r = 0; for (auto &c: s) { ans[r].push_back(c); r = (r + 1) % n; } return ans; }
Time complexity for this simple string cipher is O(N) where N is the number of the characters in the original string.
String Cipher Algorithms
- Simple Vigenère Cipher in C++
- A Simple Atbash Cipher
- Simple Vertical Cipher Algorithm
- Caesar Cipher Algorithm in C++
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
327 wordsloading...
Last Post: Teaching Kids Programming - Introduction to Math Induction
Next Post: Compute Largest Product of Contiguous Digits