mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-21 22:51:07 +08:00
Update 1002.查找常用字符.md
Add TypeScript solution.
This commit is contained in:
@ -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 {
|
||||
|
Reference in New Issue
Block a user