• Leetcode 916 单词子集 ASC码计数


      通过 ASC 码计数进行子集判断,JAVA:

        public final List<String> wordSubsets(String[] A, String[] B) {
            List<String> reList = new LinkedList<String>();
            int[] bChars = new int[26];
            for (String b : B) {
                int[] currentBChars = getChars(b);
                for (int i = 0; i < 26; i++) {
                    bChars[i] = Math.max(bChars[i], currentBChars[i]);
                }
            }
            for (String a : A) {
                boolean isSub = true;
                int[] aChars = getChars(a);
                for (int i = 0; i < 26; i++) {
                    if (aChars[i] < bChars[i]) {
                        isSub = false;
                        break;
                    }
                }
                if (isSub) reList.add(a);
            }
            return reList;
        }
    
        private final int[] getChars(String s) {
            int[] charsArr = new int[26];
            for (char c : s.toCharArray()) {
                charsArr[c - 'a']++;
            }
            return charsArr;
        }

     

     /**
     * @param {string[]} A
     * @param {string[]} B
     * @return {string[]}
     */
    var wordSubsets = function (A, B) {
        let reArr = [], bChars = new Array(26).fill(0);
        for (let i = 0; i < B.length; i++) {
            let b = B[i], currentBChars = getChars(b);
            for (let i = 0; i < 26; i++) {
                bChars[i] = Math.max(bChars[i], currentBChars[i]);
            }
        }
        for (let i = 0; i < A.length; i++) {
            let a = A[i], aChars = getChars(a), isSub = true;
            for (let i = 0; i < 26; i++) {
                if (aChars[i] < bChars[i]) {
                    isSub = false;
                    break;
                }
            }
            if (isSub) reArr.push(a);
        }
        return reArr;
    };
    
    var getChars = function (s) {
        let reArr = new Array(26).fill(0);
        for (let i = 0; i < s.length; i++) {
            reArr[s[i].charCodeAt() - 97]++;
        }
        return reArr;
    }

  • 相关阅读:
    【模板】二分
    电脑桌面美化
    浪在ACM新春大作战
    【递归入门】组合+判断素数:dfs(递归)
    【递归入门】组合的输出:dfs
    01背包问题:DP
    [蓝桥杯][历届试题]回文数字
    洛谷 P1706 全排列问题 :STL / dfs
    【模板】DFS
    洛谷 P1781 宇宙总统:sort(string)
  • 原文地址:https://www.cnblogs.com/niuyourou/p/14127163.html
Copyright © 2020-2023  润新知