File tree 2 files changed +42
-31
lines changed
2 files changed +42
-31
lines changed Original file line number Diff line number Diff line change
1
+ class Trie (object ):
2
+ def __init__ (self ):
3
+ """
4
+ Initialize your data structure here.
5
+ """
6
+ self .root = {}
7
+ self .char_cnt = 0 # 统计 a - z 字符个数
8
+ self .word_cnt = 0 # 统计结尾符 # 个数
9
+ def insert (self , word ):
10
+ """
11
+ Inserts a word into the trie.
12
+ :type word: str
13
+ :rtype: None
14
+ """
15
+ node = self .root
16
+ for char in word : # word 入树
17
+ node = node .setdefault (char , {})
18
+
19
+ if not node : # not node 就代表当前 word 不是之前某一 word 的后缀
20
+ self .word_cnt += 1
21
+ self .char_cnt += len (word )
22
+ node ["end" ] = True
23
+
24
+ class Solution (object ):
25
+ def minimumLengthEncoding (self , words ):
26
+ """
27
+ :type words: List[str]
28
+ :rtype: int
29
+ """
30
+ ttree = Trie ()
31
+
32
+ for word in sorted (words , key = lambda x :len (x ), reverse = True ):
33
+ # 按长度由大到小排序,再将每个 word 反向插入树
34
+ ttree .insert (word [::- 1 ])
35
+ # print ttree.char_cnt, ttree.word_cnt
36
+ return ttree .char_cnt + ttree .word_cnt
Original file line number Diff line number Diff line change 1
1
class Solution (object ):
2
- def hasGroupsSizeX ( self ,deck ):
2
+ def hasGroupsSizeX (self , deck ):
3
3
"""
4
4
:type deck: List[int]
5
5
:rtype: bool
6
6
"""
7
- if len (deck ) <= 0 :
8
- return False
9
- deck .sort ()
10
- print deck
11
- a = deck [0 ]
12
- count = deck .count (a )
13
- if count < 2 :
14
- return False
15
- for j in range (2 , count + 1 ):
16
- if len (deck ) % j != 0 :
17
- continue
18
- print "invalid length" ,j ,len (deck )
19
- for i in range (0 , len (deck ),j ):
20
- temp = deck [i ]
21
- flag = 0
22
- print i ,temp
23
- for k in range (i ,i + j ):
24
- if deck [k ] != temp :
25
- flag = 1
26
- print "not the same" ,deck [k ],temp
27
- if flag == 1 :
28
- break
29
- if flag == 1 :
30
- continue
31
- return True
32
- return False
33
-
34
-
35
-
36
-
7
+ def gcd (a , b ):
8
+ while b :
9
+ a , b = b , a % b
10
+ return a
11
+ return functools .reduce (gcd , collections .Counter (deck ).values ()) >= 2
You can’t perform that action at this time.
0 commit comments