Encode given String by inserting in Matrix column-wise and printing it row-wise
Given a string S and an integer R, the task is to encode the string by first filling each character in column wise manner from top to bottom in a matrix having R rows and then printing the matrix row wise.
Examples:
Input: S = “abcdefgh”, R = 3
Output: adgbehcf
Explanation: Matrix formed is:
a d g
b e h
c f
So when printed row wise it gives the encoded string as “adgbehcf”Input: S = “GeeksForGeeks”, R = 5
Output: GFeeokerskGse
Explanation: Pattern formed is:
G f e
e o k
e r s
k G
s
Approach: The approach is to use an array of string temp of size R. Traverse every character of string S and add it at the end of the string at i%R index of the array temp. Now traverse the temp array row wise to get the encoded string.
Below is the implementation of the above approach.
C++14
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to encode the stringstring printRowWise(string S, int R){ vector<string> temp(R); string ans; for (int i = 0; i < S.length(); i++) temp[i % R].push_back(S[i]); for (int i = 0; i < R; i++) { for (int j = 0; j < temp[i].size(); j++) ans.push_back(temp[i][j]); } return ans;} // Driver codeint main(){ string S = "GeeksForGeeks"; int R = 5; cout << printRowWise(S, R); return 0;} |
GFeeokerskGse
Time Complexity: O(N) where N is the length of the string
Auxiliary Space: O(N)


 (1).png)