Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1503295

Browse files
Valid Anagram
1 parent e93a1ee commit 1503295

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

‎0242_validAnagram.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} s First string.
3+
* @param {string} t Second string
4+
* @return {boolean} Are strings anagrams of each other.
5+
* @summary Valid Anagram {@link https://leetcode.com/problems/valid-anagram/solution/}
6+
* @description Given two input strings return true if they are anagrams.
7+
* Space O(1) - Always two arrays of 26 items.
8+
* Time O(n) - Only loop two arrays if both strings are euqal length, hence 2 loops of n.
9+
*/
10+
const isAnagram = (s, t) => {
11+
if (s.length !== t.length) return false;
12+
13+
const OFFSET = 'a'.charCodeAt();
14+
const ENGLISH_LETTERS_COUNT = 26;
15+
16+
const countsS = Array(ENGLISH_LETTERS_COUNT);
17+
const countsT = Array(ENGLISH_LETTERS_COUNT);
18+
19+
for (let i = 0; i < s.length; i++) {
20+
const index = s[i].charCodeAt() - OFFSET;
21+
22+
countsS[index] = countsS[index] ? countsS[index] + 1 : 1;
23+
}
24+
25+
for (let i = 0; i < t.length; i++) {
26+
const index = t[i].charCodeAt() - OFFSET;
27+
28+
countsT[index] = countsT[index] ? countsT[index] + 1 : 1;
29+
}
30+
31+
return countsS.every((count, index) => count === countsT[index]);
32+
};

‎0438_findAllAnagramsInAString.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
* @return {number[]} Array with indexes of all substrings that are anagrams of word.
55
* @summary Find All Anagrams in a String {@link https://leetcode.com/problems/find-all-anagrams-in-a-string/}
66
* @description Given two input strings return indexes of substrings that are anagrams of second input.
7-
* Space O(A+B) - A length of string 'word', B length of string 'stream'.
8-
* Time O(1) - Two new arrays, each of 26 elements.
7+
* Space O(1) - Two new arrays, each of 26 elements.
8+
* Time O(A+B) - A length of string 'word', B length of string 'stream'.
99
*/
1010
const findAnagrams = (stream, word) => {
1111
const counts = Array(26);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /