Skip to content

Commit e18ac49

Browse files
committed
Runtime 664 ms (Top 53.85%) | Memory 14.0 MB (Top 61.54%)
1 parent fbeeda6 commit e18ac49

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
class Solution:
2-
@lru_cache(None)
3-
def f(self,i):
4-
return 1 if i <= 1 else (self.f(i-1)*i) % (10**9+7)
1+
from math import gcd
52

6-
def makeStringSorted(self, s):
7-
N, n, out = 10**9 + 7, len(s), 0
8-
cnt = [0]*26
9-
for i in range(n-1, -1, -1):
10-
ind = ord(s[i]) - ord("a")
11-
cnt[ind] += 1
12-
ans = sum(cnt[:ind]) * self.f(n-i-1)
13-
for j in range(26):
14-
ans = ans * pow(self.f(cnt[j]), N-2, N) % N
15-
out += ans
16-
return out % N
3+
class Solution:
4+
def makeStringSorted(self, s: str) -> int:
5+
s = [ord(c) - ord('a') for c in s]
6+
ans, MOD = 0, 10 ** 9 + 7
7+
cnt, t, d, step = [0] * 26, 1, 1, 1
8+
cnt[s[-1]] = 1
9+
for c in reversed(s[:-1]):
10+
d *= (cnt[c] + 1)
11+
t *= step
12+
g = gcd(d, t)
13+
d //= g
14+
t //= g
15+
ans = (ans + t * sum(cnt[i] for i in range(c)) // d) % MOD
16+
cnt[c] += 1
17+
step += 1
18+
return ans

0 commit comments

Comments
 (0)