File tree Expand file tree Collapse file tree 1 file changed +5
-16
lines changed
Python/chapter01/1.2 - Check Perm Expand file tree Collapse file tree 1 file changed +5
-16
lines changed Original file line number Diff line number Diff line change 4
4
Given two strings, write a method to decide if one is a permutation of the other.
5
5
"""
6
6
import unittest
7
+ import collections
7
8
from typing import Callable
8
9
9
10
@@ -27,30 +28,18 @@ def check_permutation(s1: str, s2: str) -> bool:
27
28
:param s2: string of size m
28
29
:return: True if s1 is a permutation of s2, False otherwise
29
30
"""
30
- # permutations must be of equal length, one-to-one
31
- if len (s1 ) != len (s2 ):
32
- return False
33
- freqs_s1 = {}
34
31
# build histogram of seen characters in s1
35
32
# using histogram because string could have repeated characters
36
- for c in s1 :
37
- if c not in freqs_s1 :
38
- freqs_s1 [c ] = 1
39
- continue
40
- freqs_s1 [c ] += 1
33
+ freqs_s1 = collections .Counter (s1 )
41
34
42
- freqs_s2 = {}
35
+ # check if s2 characters exist in s1
43
36
for c in s2 :
44
37
# if character in s2 not in s1, then this is not a permutation
45
38
if c not in freqs_s1 :
46
39
return False
47
- # otherwise, populate as normal
48
- if c not in freqs_s2 :
49
- freqs_s2 [c ] = 1
50
- continue
51
- freqs_s2 [c ] += 1
52
40
53
- # compare frequences of characters for s1 and s2
41
+ freqs_s2 = collections .Counter (s2 )
42
+ # compare frequencies of characters for s1 and s2
54
43
for key , val in freqs_s1 .items ():
55
44
if val != freqs_s2 [key ]:
56
45
# character counts between s1 and s2 don't match
You can’t perform that action at this time.
0 commit comments