給你一份『詞匯表』(字符串?dāng)?shù)組) words
和一張『字母表』(字符串) chars
。
假如你可以用 chars
中的『字母』(字符)拼寫出 words
中的某個『單詞』(字符串)搂抒,那么我們就認(rèn)為你掌握了這個單詞虽风。
注意:每次拼寫時枣氧,chars
中的每個字母都只能用一次遂填。
返回詞匯表 words 中你掌握的所有單詞的 長度之和赡茸。
示例 :
輸入: words = ["cat","bt","hat","tree"], chars = "atach"
輸出: 6
解釋: 可以形成字符串 "cat" 和 "hat"森缠,所以答案是 3 + 3 = 6。
輸入: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
輸出: 10
解釋: 可以形成字符串 "hello" 和 "world"奕谭,所以答案是 5 + 5 = 10涣觉。
思路:
- 簡單的映射數(shù)組問題, 重點(diǎn)在于每次遍歷, 需要創(chuàng)建一個臨時計數(shù)的列表
- 好久沒寫東西了, 最近能稍微寫寫
代碼:
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() == 0)
return intervals;
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
Interval ii, jj;
public int countCharacters(String[] words, String chars) {
int res = 0;
int[] tempChars = new int[26];
int[] useCount;
// 字母表映射數(shù)組
for (int i = 0; i < chars.length(); i++) {
tempChars[chars.charAt(i) - 'a']++;
}
int t;
for (String word : words) {
useCount = new int[26];
res += word.length();
for (int i = 0; i < word.length(); i++) {
t = word.charAt(i)- 'a';
useCount[t]++;
if (useCount[t] > tempChars[t]) {
res -= word.length();
break;
}
}
}
return res;
}
分析:
- 先遍歷獲取映射數(shù)組, 得到每個字母的使用次數(shù)
- 遍歷單詞列表, 每個單詞創(chuàng)建一個計數(shù)數(shù)組
- 每個單詞字母,計數(shù)數(shù)組統(tǒng)計出現(xiàn)次數(shù), 并做判斷: 若當(dāng)前次數(shù)大于映射數(shù)組次數(shù), 則返回(表示字母數(shù)目不足,無法創(chuàng)建單詞)
總結(jié):
- 非常簡單的一道題, 效率排行榜的解題思路也大同小異