Skip to content

Commit 94bf891

Browse files
authored
Update 1002.查找常用字符.md
Add TypeScript solution.
1 parent a27d1a4 commit 94bf891

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

problems/1002.查找常用字符.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,41 @@ var commonChars = function (words) {
253253
return res
254254
};
255255
```
256+
257+
TypeScript
258+
```ts
259+
function commonChars(words: string[]): string[] {
260+
let result: string[] = [];
261+
if (words.length === 0) return result;
262+
const size: number = 26;
263+
const hash: number[] = new Array(size).fill(0);
264+
const otherHash: number[] = new Array(size).fill(0);
265+
let pivot: number = 'a'.charCodeAt(0);
266+
// First word
267+
for (let character of words[0]) {
268+
hash[character.charCodeAt(0) - pivot]++;
269+
}
270+
// Other words
271+
for (let i = 1; i < words.length; i++) {
272+
for (let character of words[i]) {
273+
otherHash[character.charCodeAt(0) - pivot]++;
274+
}
275+
// Update the first hash with min
276+
for (let j = 0; j < size; j++) {
277+
hash[j] = Math.min(hash[j], otherHash[j]);
278+
}
279+
// Reset otherHash
280+
otherHash.fill(0);
281+
}
282+
// Construct the result
283+
hash.forEach((element, index) => {
284+
while (element-- > 0) {
285+
result.push(String.fromCharCode(index + pivot));
286+
}
287+
});
288+
return result;
289+
}
290+
```
256291
GO
257292
```golang
258293
func commonChars(words []string) []string {

0 commit comments

Comments
 (0)