-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkPermutation_one_str_is_perm_of_other.py
73 lines (52 loc) · 1.37 KB
/
checkPermutation_one_str_is_perm_of_other.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 16:54:11 2019
@author: Akshita
Check Permutation: Given two strings, write a method to decide if one is a
permutations of the other.
"""
import time
from collections import defaultdict
def check_permutation(A,B):
"""
O(NlogN)
"""
if len(A) != len(B):
return False
A = sorted(A)
B = sorted(B)
for i in range(len(A)):
if A[i] != B[i]:
return False
return True
def check_permutation_2(A,B):
"""
O(N)
"""
if len(A) != len(B):
return False
Adict = defaultdict(int)
Bdict = defaultdict(int)
for char in A:
Adict[char] +=1
for char in B:
Bdict[char] += 1
if len(Adict) != len(Bdict):
return False
for k,v in Adict.items():
if Bdict[k] != v:
return False
return True
def main():
A = 'tacocat'
B = 'catttco'
start = time.perf_counter()
print(check_permutation(A,B))
end = time.perf_counter()
print('For O(NlogN) fuction, time taken is: {0:.6f}'.format(end-start))
start = time.perf_counter()
print(check_permutation_2(A,B))
end = time.perf_counter()
print('For O(N) fuction, time taken is: {0:.6f}'.format(end-start))
if __name__ == '__main__':
main()