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["af", "bg", "ch", "di", "e"]Explanation
This reads vertically as:["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. %.
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) —
Last Post: Teaching Kids Programming - Introduction to Math Induction
Next Post: Compute Largest Product of Contiguous Digits