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

พิมพ์สตริงในรูปแบบ Plus (+) ในเมทริกซ์ C++

ได้รับสตริง str งานคือพิมพ์สตริงในรูปแบบเครื่องหมายบวก (+) ในเมทริกซ์ สตริงจะแสดงแนวนอนและแนวตั้ง ตัดกันที่จุดกึ่งกลาง ส่วนที่เหลือเติม 'x'

เงื่อนไข: สตริงต้องมีความยาว คี่ (odd length) เท่านั้น จึงจะมีจุดกึ่งกลางชัดเจน

ตัวอย่าง

Input: "TUTOR" (ความยาว 5)

Output:

x x T x x
x x U x x
T U T O R
x x O x x
x x R x x

Input: "Point" (ความยาว 5)

Output:

x x P x x
x x o x x
P o i n t
x x n x x
x x t x x

Input: "this" (ความยาว 4 - คู่)

Output: Pattern not possible

แนวทางแก้ปัญหา

  1. ตรวจสอบความยาวสตริง – ต้องเป็นคี่
  2. สร้างเมทริกซ์ n×n เติม 'x' ทั้งหมด
  3. คำนวณจุดกึ่งกลาง mid = n / 2
  4. วางสตริงในแถวกลาง: matrix[mid][j] = str[j]
  5. วางสตริงในคอลัมน์กลาง: matrix[i][mid] = str[i]
  6. พิมพ์เมทริกซ์

ตัวอย่างโค้ด (แก้ไขให้ compile ได้)

#include <iostream>
#include <vector>
#include <string>
using namespace std;

void printPlusPattern(const string& str) {
    int n = str.length();
    
    if (n % 2 == 0) {
        cout << "Pattern not possible (string length must be odd)" << endl;
        return;
    }
    
    vector<vector<char>> matrix(n, vector<char>(n, 'x'));
    int mid = n / 2;
    
    // วางแนวนอน (แถวกลาง)
    for (int j = 0; j < n; j++) {
        matrix[mid][j] = str[j];
    }
    
    // วางแนวตั้ง (คอลัมน์กลาง)
    for (int i = 0; i < n; i++) {
        matrix[i][mid] = str[i];
    }
    
    // พิมพ์
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << matrix[i][j] << ' ';
        }
        cout << endl;
    }
}

int main() {
    printPlusPattern("TUTOR");
    cout << endl;
    printPlusPattern("Point");
    cout << endl;
    printPlusPattern("this");
    return 0;
}

ผลลัพธ์

x x T x x
x x U x x
T U T O R
x x O x x
x x R x x

x x P x x
x x o x x
P o i n t
x x n x x
x x t x x

Pattern not possible (string length must be odd)

การปรับปรุงจากโค้ดต้นฉบับ

  • ใช้ vector<vector<char>> แทน array ขนาดคงที่ max[100]
  • แก้ไข logic การเข้าถึง index (โค้ดต้นฉบับมี bug: sizeof(str)/sizeof(str[0]) ให้ขนาด array ไม่ใช่ความยาว string)
  • เพิ่มข้อความ error ที่ชัดเจน
  • รองรับสตริงความยาวใดก็ได้ (ไม่จำกัด 100)

ความซับซ้อน

  • เวลา: O(n²) – สร้างและพิมพ์เมทริกซ์ n×n
  • พื้นที่: O(n²) – เก็บเมทริกซ์

ขยายความ: พิมพ์เฉพาะกรอบ (Memory Efficient)

หากต้องการแค่พิมพ์ ไม่ต้องเก็บเมทริกซ์:

void printPlusPatternNoMatrix(const string& str) {
    int n = str.length();
    if (n % 2 == 0) { cout << "Pattern not possible\n"; return; }
    int mid = n / 2;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == mid) cout << str[j];
            else if (j == mid) cout << str[i];
            else cout << 'x';
            if (j < n-1) cout << ' ';
        }
        cout << endl;
    }
}

พื้นที่ลดเหลือ O(1)