-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfindMostFrequent.py
56 lines (52 loc) · 935 Bytes
/
findMostFrequent.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
from collections import defaultdict
def findMostFrequent(s):
# O(n)
dic = defaultdict(int)
count = 0
res = ""
if not s:
return res
for char in s:
char = char.lower()
if not char.isalpha():
continue
if char == " ":
continue
dic[char] += 1
if dic[char] > count:
count = dic[char]
res = char
print res, count
def findMostFrequent2(s):
# O(n)
dic = defaultdict(int)
count1 = 0
count2 = 0
c1 = ""
c2 = ""
if not s:
return res
for char in s:
char = char.lower()
if not char.isalpha():
continue
if char == " ":
continue
dic[char] += 1
if dic[char] > count1:
if char == c1:
count1 += 1
else:
count2 = count1
c2 = c1
count1 = dic[char]
c1 = char
elif dic[char] > count2:
count2 = dic[char]
c2 = char
if count1 - count2 >= len(s) - s.index(char):
break
print c1, c2, count1, count2
s = "addassxvwrcvssd"
findMostFrequent(s)
findMostFrequent2(s)