java赛选重复的字母,查找带有重复字母的单词(排列)的排名

小编典典

注意:此答案适用于基于1的排名,如示例中所隐含指定。这是一些至少可用于所提供的两个示例的Python。关键事实是suffixperms * ctr[y]// ctr[x]排列的数量,其首字母为y的(i + 1)后缀perm。

from collections import Counter

def rankperm(perm):

rank = 1

suffixperms = 1

ctr = Counter()

for i in range(len(perm)):

x = perm[((len(perm) - 1) - i)]

ctr[x] += 1

for y in ctr:

if (y < x):

rank += ((suffixperms * ctr[y]) // ctr[x])

suffixperms = ((suffixperms * (i + 1)) // ctr[x])

return rank

print(rankperm('QUESTION'))

print(rankperm('BOOKKEEPER'))

Java版本:

public static long rankPerm(String perm) {

long rank = 1;

long suffixPermCount = 1;

java.util.Map charCounts =

new java.util.HashMap();

for (int i = perm.length() - 1; i > -1; i--) {

char x = perm.charAt(i);

int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;

charCounts.put(x, xCount);

for (java.util.Map.Entry e : charCounts.entrySet()) {

if (e.getKey() < x) {

rank += suffixPermCount * e.getValue() / xCount;

}

}

suffixPermCount *= perm.length() - i;

suffixPermCount /= xCount;

}

return rank;

}

无等级排列:

from collections import Counter

def unrankperm(letters, rank):

ctr = Counter()

permcount = 1

for i in range(len(letters)):

x = letters[i]

ctr[x] += 1

permcount = (permcount * (i + 1)) // ctr[x]

# ctr is the histogram of letters

# permcount is the number of distinct perms of letters

perm = []

for i in range(len(letters)):

for x in sorted(ctr.keys()):

# suffixcount is the number of distinct perms that begin with x

suffixcount = permcount * ctr[x] // (len(letters) - i)

if rank <= suffixcount:

perm.append(x)

permcount = suffixcount

ctr[x] -= 1

if ctr[x] == 0:

del ctr[x]

break

rank -= suffixcount

return ''.join(perm)

2020-07-28

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值