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

Letter Case Permutation ใน C++

สมมติเรามีสตริงที่มีตัวอักษรและตัวเลข เราต้องสร้าง combinations ทั้งหมดของสตริงนั้นโดยใช้ uppercase และ lowercase ของตัวอักษรที่มีอยู่ในสตริง ถ้าสตริงมีแต่ตัวเลข จะคืนค่าแค่ตัวเลขนั้น เช่น สตริง "1ab2" จะได้ ["1ab2", "1Ab2", "1aB2", "1AB2"]

เพื่อแก้ปัญหานี้ เราจะใช้ recursive approach ฟังก์ชันรับ index parameter เริ่มทำงานจาก index นั้น และรับ temp string จนถึงที่สร้างผลลัพธ์แล้ว เมื่อ index เท่ากับความยาวสตริง ให้คืน temp string สำหรับ index ที่กำหนด ถ้าเป็นตัวพิมพ์เล็ก ให้ทำเป็นพิมพ์ใหญ่ และกลับกัน แล้วเรียกซ้ำ

โปรแกรมตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

void print_vector(vector<string> v) {
    cout << "[";
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << ", ";
    }
    cout << "]" << endl;
}

class Solution {
public:
    vector<string> res;
    void solve(string s, int idx = 0, string temp = "") {
        if (idx == s.size()) {
            res.push_back(temp);
            return;
        }
        solve(s, idx + 1, temp + s[idx]);
        int diff = 'a' - 'A';
        if (s[idx] >= 'a' && s[idx] <= 'z') {
            char x = (s[idx] - diff);
            solve(s, idx + 1, temp + x);
        }
        else if (s[idx] >= 'A' && s[idx] <= 'Z') {
            char x = (s[idx] + diff);
            solve(s, idx + 1, temp + x);
        }
    }
    vector<string> letterCasePermutation(string S) {
        res.clear();
        solve(S);
        return res;
    }
};

main() {
    Solution ob;
    print_vector(ob.letterCasePermutation("1ab2"));
    print_vector(ob.letterCasePermutation("9876"));
}

Input

"1ab2" "9876"

Output

[1ab2, 1aB2, 1Ab2, 1AB2, ]
[9876, ]