Skip to content

Commit

Permalink
Update 1002.查找常用字符.md
Browse files Browse the repository at this point in the history
Add TypeScript solution.
  • Loading branch information
Aaron-Lin-74 authored Mar 6, 2022
1 parent a27d1a4 commit 94bf891
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions problems/1002.查找常用字符.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 94bf891

Please sign in to comment.