ในปัญหานี้ เราได้รับสตริงที่เป็นลำดับของอักขระ และเราได้รับความยาวของรูปแบบซิกแซก และเราต้องพิมพ์สตริงการต่อของสตริงซิกแซกนี้ใน 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
คำอธิบาย − รูปแบบซิกแซกสำหรับสตริงที่มีสามแถวคือ −
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