>[success] # 刷題前知識補充
在做字母字符問題時候可以利用**ASCII** 對應的字符集作為數組腳標,用來記錄出現次數,例如英文小寫單詞**a-z**,所對應的字符集**97-122**,舉個例子現在要記錄`azsxzxxs` 中每個字符出現
1. 先創建一個26長度數組
2. 將字符轉換對應ascii碼,記錄到對應數組位置
~~~
// 只會有小寫字母
const w = 'azsxzxxs'
function getWordCounts(words) {
// 創建一個26 長度數組
const ls = new Array(26).fill(0)
// 因為小寫a 是從97開始
const ascii_a = 'a'.charCodeAt()
// 循環每個單詞找到對應的ascii碼記錄保存
for (let i = 0; i < words.length; i++) {
// charCodeAt 參數是當前字符所應轉換為ascii,減掉97
const idx = words.charCodeAt(i) - ascii_a
ls[idx]++
}
// 打印每個字符出現此時
return ls.reduce((acc, cur, index) => {
// 轉換將ascii 碼對應碼轉換為對應小寫單詞
if (cur) {
const w = String.fromCharCode(index + ascii_a)
acc[w] = cur
}
return acc
}, {})
}
console.log(getWordCounts(w)) // { a: 1, s: 2, x: 3, z: 2 }
~~~
* 利用Map 映射來做
~~~
// 只會有小寫字母
const w = 'azsxzxxs'
function getWordCounts(words) {
const obj = {}
for (let w of words) {
if (!obj[w]) obj[w] = 0
obj[w]++
}
return obj
}
console.log(getWordCounts(w))
~~~
- 刷題準備
- 統計數組中元素出現次數
- Leetcode -- 442數組中重復的數據
- leetcode -- 448 找到所有數組中消失的數字
- 字符類似題
- Leetcode -- 1002 查找共用字符
- Leetcode -- 1370上升下降字符串
- 指針類題解
- Leetcode -- 283 移動零
- Leetcode -- 26. 刪除有序數組中的重復項
- Leetcode -- 80. 刪除有序數組中的重復項 II
- Leetcode -- 27. 移除元素
- Leetcode -- 344. 反轉字符串
- Leetcode -- 125 驗證回文串
- Leetcode -- 11 盛最多水的容器
- Leetcode -- 1480. 一維數組的動態和