File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
JavaScript/chapter01/1.2 - Check Perm Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*Given two strings, write a method to decide
2
+ if one is apermutation of the other permutation:*/
3
+
4
+ const isPermutation = ( str1 , str2 ) => {
5
+ if ( str1 . length !== str2 . length ) {
6
+ return false ;
7
+ }
8
+ const obj1 = determineCharCount ( str1 ) ;
9
+ const obj2 = determineCharCount ( str2 ) ;
10
+ for ( let char of str1 ) {
11
+ if ( obj1 [ char ] !== obj2 [ char ] ) {
12
+ return false ;
13
+ }
14
+ }
15
+ return true ;
16
+ //******** helper function ******
17
+ function determineCharCount ( string ) {
18
+ const obj = { } ;
19
+ for ( let char of string ) {
20
+ if ( obj [ char ] !== undefined ) {
21
+ obj [ char ] ++ ;
22
+ } else {
23
+ obj [ char ] = 1 ;
24
+ }
25
+ }
26
+ return obj ;
27
+ }
28
+ }
29
+
30
+ // Tests:
31
+ console . log ( isPermutation ( 'abc' , 'abb' ) === false ) ;
32
+ console . log ( isPermutation ( 'abb' , 'abc' ) === false ) ;
33
+ console . log ( isPermutation ( 'aaa' , 'abc' ) === false ) ;
34
+ console . log ( isPermutation ( 'abc' , 'abcd' ) === false ) ;
35
+ console . log ( isPermutation ( 'abc' , 'bac' ) === true ) ;
36
+ console . log ( isPermutation ( '' , '' ) === true ) ;
37
+ console . log ( isPermutation ( '12' , '21' ) === true ) ;
You can’t perform that action at this time.
0 commit comments