LeetCode—3606

Approach

# 按照題目敘述尋找符合條件的字串
Find the strings that satisfy the conditions.

# 輸出要按照字典序排序
The output should be sorted in lexicographical order.

Time Complexity

# Sort
O(n * logn)

Space Complexity

# Sort
O(logn)

Code

class Solution {
public:
    vector<string> validateCoupons(vector<string>& code, vector<string>& businessLine, vector<bool>& isActive) {

        int n = code.size();
        vector<string> tmp[4], ans;

        for (int i = 0 ; i < n ; i++) {
            bool check_code = false, check_b = false;

            for (int j = 0 ; j < code[i].size() ; j++) {
                check_code = false;

                if (code[i][j] >= 'a' && code[i][j] <= 'z') {
                    check_code = true;
                }

                if (code[i][j] >= 'A' && code[i][j] <= 'Z') {
                    check_code = true;
                }

                if (code[i][j] >= '0' && code[i][j] <= '9') {
                    check_code = true;
                }

                if (code[i][j] == '_') {
                    check_code = true;
                }

                if (check_code == false) {
                    break;
                }
            }

            if (businessLine[i] == "electronics") {
                check_b = true;
            }
            else if (businessLine[i] == "grocery") {
                check_b = true;
            }
            else if (businessLine[i] == "pharmacy") {
                check_b = true;
            }
            else if (businessLine[i] == "restaurant") {
                check_b = true;
            }

            if (check_code && check_b && isActive[i]) {
                if (businessLine[i] == "electronics") {
                    tmp[0].push_back(code[i]);
                }
                else if (businessLine[i] == "grocery") {
                    tmp[1].push_back(code[i]);
                }
                else if (businessLine[i] == "pharmacy") {
                    tmp[2].push_back(code[i]);
                }
                else if (businessLine[i] == "restaurant") {
                    tmp[3].push_back(code[i]);
                }
            }
        }

        //
        for (int i = 0 ; i < 4 ; i++) {
            sort(tmp[i].begin(), tmp[i].end());

            for (int j = 0 ; j < tmp[i].size() ; j++) {
                ans.push_back(tmp[i][j]);
            }
        }

        return ans;
    }
};