在这个问题中,我们给了一个字符串,它是一个字符序列。并给出了Z字形模式的长度,我们必须在n行中打印该Z字形字符串的连接字符串。
让我们看一些例子,以更好地理解这个概念,
Input : string = ‘STUVWXYZ’ n = 2. Output : SUWYTVXZ
说明-2行模式的字符串的曲折模式为-
S U W Y T V X Z
此锯齿形模式的串联是-SUWYTVXZ。
Input : string = ABCDEFGH n = 3 Output: ADGBEHCF
说明-三行字符串的锯齿形为-
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