C++ 中列印 N 行之字形字串的拼接
在這個問題中,我們給定一個字串,它是一系列字元。我們還給定了之字形圖案的長度,並且需要列印這個之字形字串在 n 行中的拼接字串。
讓我們看幾個例子來更好地理解這個概念,
示例
Input : string = ‘STUVWXYZ’ n = 2. Output : SUWYTVXZ
解釋 - 字串的 2 行之字形圖案如下:
S U W Y T V X Z
這個之字形圖案的拼接是 - SUWYTVXZ。
示例
Input : string = ABCDEFGH n = 3 Output: ADGBEHCF
解釋 - 字串的 3 行之字形圖案如下:
A E B D F H C G
之字形圖案的拼接是 - AEBDFHCG
現在我們知道了問題,讓我們設計一個解決方案。在這裡,我們將向下傳播字串的下一個元素,直到行數達到 n。然後向上傳播直到行數變為零,然後再次向下。最後,列印每一行的結果以獲得解決方案。
基於這個概念,讓我們推匯出一個可以解決問題的演算法,
演算法
Step 1 : Take an array of string of size n, string arr[n], row for current row no. i.e. string in the array and the direction as 1(indicating downward traversal). Step 2 : Traverse the string and follow step 3 - 7. For every character of the string. Step 3 : Append the character to the current string in the array based on the value of row. Step 4 : If row = n-1, direction = 1. Step 5 : if row = 0, direction = -1. Step 6 : if direction = 1, row++ . Step 7 : else row--. Step 8 : print all string on the array from 0 to n-1 in sequence.
示例
現在基於這個演算法建立一個程式來實現我們的解決方案 -
#include<bits/stdc++.h> using namespace std; void ZigZagConcatenationString(string str, int n){ if (n == 1){ cout << str; return; } int len = str.length(); string arr[n]; int row = 0; int direction = 1; bool down; for (int i = 0; i < len; ++i){ arr[row].push_back(str[i]); if (row == n-1) direction = -1; else if (row == 0) direction = 1; (direction == 1)? (row++): (row--); } for (int i = 0; i < n; ++i) cout << arr[i]; } int main(){ string str = "ABCDEFGH"; int n = 3; ZigZagConcatenationString(str, n); return 0; }
輸出
AEBDFHCG
廣告