1.題目描述
給你一個由不同字符組成的字符串 allowed 和一個字符串數(shù)組 words 。如果一個字符串的每一個字符都在 allowed 中,就稱這個字符串是 一致字符串 。
請你返回 words 數(shù)組中 一致字符串 的數(shù)目。
示例 1:
輸入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
輸出:2
解釋:字符串 "aaab" 和 "baa" 都是一致字符串,因為它們只包含字符 'a' 和 'b' 。
示例 2:
輸入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
輸出:7
解釋:所有字符串都是一致的。
示例 3:
輸入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
輸出:4
解釋:字符串 "cc","acd","ac" 和 "d" 是一致字符串。
2.解題思路與代碼
2.1 解題思路
非常簡單的一道字符串遍歷題,首先我們使用一個長度為 26 的 boolean 型的數(shù)組 tmp 存放 allowed 中每個字符是否出現(xiàn),如果出現(xiàn)就在 tmp[allowed.charAt(i)-'a'] 的位置上設置為 true,表示字母出現(xiàn)過。然后遍歷字符串數(shù)組 words 并對數(shù)組中每個字符串的字符進行判斷,如果每個字符在 tmp 中的位置上都是 true,表示每個字符都在 allowed 中存在,統(tǒng)計結果加 1,否則存在不一致的字母,不計數(shù)。
2.2 代碼
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
boolean[] tmp = new boolean[26];
int ans = 0;
for (int i = 0; i < allowed.length(); i++) {
tmp[allowed.charAt(i) - 'a'] = true;
}
outer:for (String word : words) {
for (int i = 0; i < word.length(); i++) {
if (!tmp[word.charAt(i)-'a']) {
continue outer;
}
}
ans++;
}
return ans;
}
}
2.3 測試結果
通過測試

測試結果
3.總結
- 使用 boolean 類型數(shù)組統(tǒng)計 allowed 中字符出現(xiàn)的情況
- 遍歷 words 數(shù)組并并 allowed 中的字符進行比較