3606. Coupon Code Validator

题目 3606. Coupon Code Validator

image-ff556526

思路分析

代码实现

import java.util.*;

class Solution {
    // 定义一个内部辅助类,用来存储有效优惠券的信息
    private static class ValidCoupon {
        String code;
        String businessLine;
        int priority; // 用于业务线的排序权重

        public ValidCoupon(String code, String businessLine, int priority) {
            this.code = code;
            this.businessLine = businessLine;
            this.priority = priority;
        }
    }

    public List<String> findValidCoupons(String[] code, String[] businessLine, boolean[] isActive) {
        List<ValidCoupon> validList = new ArrayList<>();
        int n = code.length;

        // 1. 遍历并筛选
        for (int i = 0; i < n; i++) {
            // 条件 3: isActive 必须为 true
            if (!isActive[i]) continue;

            // 条件 2: 检查 businessLine 是否合法,并获取优先级
            int priority = getBusinessPriority(businessLine[i]);
            if (priority == -1) continue; // -1 表示不是这四个类别之一

            // 条件 1: 检查 code 格式
            if (isValidCode(code[i])) {
                validList.add(new ValidCoupon(code[i], businessLine[i], priority));
            }
        }

        // 2. 排序
        // 规则:先按 priority (业务线) 升序,如果相同,再按 code (字典序) 升序
        Collections.sort(validList, (a, b) -> {
            if (a.priority != b.priority) {
                return a.priority - b.priority;
            } else {
                return a.code.compareTo(b.code);
            }
        });

        // 3. 提取结果
        List<String> result = new ArrayList<>();
        for (ValidCoupon coupon : validList) {
            result.add(coupon.code);
        }
        return result;
    }

    // 辅助函数:获取业务线的优先级
    private int getBusinessPriority(String s) {
        switch (s) {
            case "electronics": return 0;
            case "grocery":     return 1;
            case "pharmacy":    return 2;
            case "restaurant":  return 3;
            default:            return -1; // 无效类别
        }
    }

    // 辅助函数:检查 code 格式
    private boolean isValidCode(String s) {
        // code 必须非空
        if (s == null || s.length() == 0) return false;
        // return s.matches("^[a-zA-Z0-9_]+$");
        // 遍历每个字符检查是否是字母、数字或下划线
        for (char c : s.toCharArray()) {
            boolean isAlpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
            boolean isDigit = (c >= '0' && c <= '9');
            boolean isUnderscore = (c == '_');
            
            if (!isAlpha && !isDigit && !isUnderscore) {
                return false;
            }
        }
        return true;
    }
}

同类题型

视频讲解