Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์สตริง Zig-Zag แบบ n แถวใน C++

โจทย์

ให้สตริงและจำนวนแถว n ต้องการจัดสตริงแบบ Zig-Zag (ไปลงมา) แล้วต่อสตริงแต่ละแถวเข้าด้วยกัน

ตัวอย่าง

Input: "STUVWXYZ", n=2 → ZigZag: Row0: S U W Y, Row1: T V X Z → Output: SUWYTVXZ

Input: "ABCDEFGH", n=3 → ZigZag: Row0: A E, Row1: B D F H, Row2: C G → Output: AEBDFHCG

อัลกอริทึม

Step 1: สร้างอาร์เรย์สตริง arr[n], row=0, direction=1 (ลง)
Step 2: ลูปทุกตัวอักษรในสตริง:
    - append ตัวอักษรเข้า arr[row]
    - ถ้า row == n-1: direction = -1 (ขึ้น)
    - ถ้า row == 0: direction = 1 (ลง)
    - row += direction
Step 3: พิมพ์ arr[0] + arr[1] + ... + arr[n-1]

ตัวอย่างโค้ด C++

#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, direction = 1;
    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