Update 1002.查找常用字符.md

Add TypeScript solution.
This commit is contained in:
Aaron-Lin-74
2022-03-07 10:15:06 +11:00
committed by GitHub
parent a27d1a454d
commit 94bf8916ee

View File

@ -253,6 +253,41 @@ var commonChars = function (words) {
return res
};
```
TypeScript
```ts
function commonChars(words: string[]): string[] {
let result: string[] = [];
if (words.length === 0) return result;
const size: number = 26;
const hash: number[] = new Array(size).fill(0);
const otherHash: number[] = new Array(size).fill(0);
let pivot: number = 'a'.charCodeAt(0);
// First word
for (let character of words[0]) {
hash[character.charCodeAt(0) - pivot]++;
}
// Other words
for (let i = 1; i < words.length; i++) {
for (let character of words[i]) {
otherHash[character.charCodeAt(0) - pivot]++;
}
// Update the first hash with min
for (let j = 0; j < size; j++) {
hash[j] = Math.min(hash[j], otherHash[j]);
}
// Reset otherHash
otherHash.fill(0);
}
// Construct the result
hash.forEach((element, index) => {
while (element-- > 0) {
result.push(String.fromCharCode(index + pivot));
}
});
return result;
}
```
GO
```golang
func commonChars(words []string) []string {