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; }
当你看清人们的真相,于是你知道了,你可以忍受孤独