Python程序:统计排序元音字符串
假设我们有一个数字n,我们需要找到由元音(a, e, i, o, u)组成的、大小为n的字符串数量,并且这些字符串按字典序排序。如果一个字符串s对于所有有效的索引i,s[i]都等于或在字母表中排在s[i+1]之前,则称其为字典序排序。
因此,如果输入是n = 2,则输出将是15,因为有很多这样的字符串,例如["aa", "ae", "ai", "ao", "au", "ee", "ei", "eo", "eu", "ii", "io", "iu", "oo", "ou", "uu"]。
为了解决这个问题,我们将遵循以下步骤:
- 如果n等于1,则
- 返回5
- count := 一个大小为6的数组,初始值都为1
- 对于i从3到n,执行:
- count[1] := count[1]+count[2]+count[3]+count[4]+count[5]
- count[2] := count[2]+count[3]+count[4]+count[5]
- count[3] := count[3]+count[4]+count[5]
- count[4] := count[4]+count[5]
- total := 0
- 对于i从1到5,执行:
- total := total + i*count[i]
- 返回total
示例
让我们来看下面的实现,以便更好地理解:
def solve(n): if n==1: return 5 count = [1 for i in range(6)] for i in range(3,n+1): count[1] = count[1]+count[2]+count[3]+count[4]+count[5] count[2] = count[2]+count[3]+count[4]+count[5] count[3] = count[3]+count[4]+count[5] count[4] = count[4]+count[5] total = 0 for i in range(1,6): total += i*count[i] return total n = 2 print(solve(n))
输入
2
输出
15
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP