forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k-similar-strings.py
40 lines (35 loc) · 1.12 KB
/
k-similar-strings.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
# Time: O(n * n!/(c_a!*...*c_z!), n is the length of A, B,
# c_a...c_z is the count of each alphabet,
# n = sum(c_a...c_z)
# Space: O(n * n!/(c_a!*...*c_z!)
import collections
class Solution(object):
def kSimilarity(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
def neighbors(s, B):
for i, c in enumerate(s):
if c != B[i]:
break
t = list(s)
for j in xrange(i+1, len(s)):
if t[j] == B[i]:
t[i], t[j] = t[j], t[i]
yield "".join(t)
t[j], t[i] = t[i], t[j]
q = collections.deque([A])
lookup = set()
result = 0
while q:
for _ in xrange(len(q)):
s = q.popleft()
if s == B:
return result
for t in neighbors(s, B):
if t not in lookup:
lookup.add(t)
q.append(t)
result += 1