Přeskočit na obsah
TypeScript Ace

5. Anagram

Vrať true, pokud je t anagram slova s. Anagram obsahuje přesně stejná písmena ve stejném počtu, jen v jiném pořadí.

Příklady

Vstups = "anagram", t = "nagaram"
Výstuptrue
Vstups = "rat", t = "car"
Výstupfalse
Nápověda

Spočítej výskyty písmen z s do Map<string, number>. Pak projdi t a počty odečítej. Když některý klesne pod nulu (nebo se liší délky), anagram to není.

Ukázat řešení
1function isAnagram(s: string, t: string): boolean {2  if (s.length !== t.length) return false;3  const count = new Map<string, number>();4  for (const ch of s) count.set(ch, (count.get(ch) ?? 0) + 1);5  for (const ch of t) {6    const left = (count.get(ch) ?? 0) - 1;7    if (left < 0) return false;8    count.set(ch, left);9  }10  return true;11}12 
reseni.tsTypeScript 6.0.3
Tab odsadí · Esc a Tab opustí editor
Typová kontrola

Kód se zkontroluje automaticky, jakmile se načte TypeScript.

Testy5 testů

Napiš řešení a stiskni Spustit testy.