标签:技术 长度 最大 遍历 题目 amp div highlight ...
一个热爱技术的菜鸟...用点滴的积累铸就明日的达人
题目
给定一个字符串,求解它的逆序数,字符串长度最大为1024,字母限定为{A,B,C,D}
例如:
输入:“DCBAB”
输出:8
解释:逆序串 [DC],[DB],[DA],[DB],[CB],[CA],[CB],[BA] 的总个数为逆序数
思路
从后往前遍历字符串,用count_a,count_b,count_c来表示A,B,C出现的次数,同时定义count表示最终的逆序数
具体规则:
出现A:count_a + 1
出现B:count_b + 1 & count + count_a
出现C:count_c + 1 & count + count_a + count_b
出现D:count + count_a + count_b + count_c
程序
init_value = (0, 0, 0, 0) def resolve(str_value): count_a, count_b, count_c, count = init_value for n in str_value[::-1]: if n == ‘A‘: count_a += 1 elif n == ‘B‘: count_b += 1 count += count_a elif n == ‘C‘: count_c += 1 count += count_a + count_b else: count += count_a + count_b + count_c print(count)
标签:技术 长度 最大 遍历 题目 amp div highlight ...
原文地址:http://www.cnblogs.com/sachen/p/6664498.html