1. 程式人生 > 實用技巧 >Leetcode 916 單詞子集 ASC碼計數

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;
}