Careercup - Facebook面试题 - 23869663

本文介绍了一种使用数位动态规划方法解决计算长度相同、字典序不大于给定字符串的所有sstring数量的问题。sstring是指全部由小写字母组成,任意连续两个字符不相同的字符串。通过逐位检查和累加,实现快速计算。

2014-05-02 03:37

题目链接

原题:

A string is called sstring if it consists of lowercase english letters and no two of its consecutive characters are the same. 

You are given string s of length n. Calculate the number of sstrings of length that are not lexicographically greater than s. 
Input format 
The only line of input contains the string s. It's length is not greater than 100. 
All characters of input are lowercase english letters. 

Output format: 
Print the answer of test modulo 1009 to the only line of output. 

Sample input: 
bcd 

Sample output: 
653

题目:如果一个字符串全部由小写字母组成,并且所有相邻字母都不同,那么这种字符串称为sstring。给定一个字符串,请统计与此字符串长度相同,且字典序不大于该字符串的所有sstring的个数。由于结果可能很大,所以结果对1009取余。

解法:这是典型的数位动态规划题目了。由于相邻字母不能相同,那么dp[i] = dp[i - 1] * (26 - 1)。对于给定的字符串,逐位进行统计和累加即可。要注意给定的字符串有可能不是sstring,也可能是,所以得加以检查。

代码:

 1 // http://www.careercup.com/question?id=23869663
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 int countSString(const string &s, const int mod)
 8 {
 9     vector<int> v;
10     int i, n;
11     
12     n = (int)s.length();
13     v.resize(n);
14     v[0] = 1 % mod;
15     for (i = 1; i < n; ++i) {
16         v[i] = v[i - 1] * 25 % mod;
17     }
18     
19     int count = 0;
20     char prev = 'z' + 1;
21     for (i = 0; i < n; ++i) {
22         if (prev >= s[i]) {
23             count = (count + (s[i] - 'a') * v[n - 1 - i]) % mod;
24         } else {
25             count = (count + (s[i] - 'a' - 1) * v[n - 1 - i]) % mod;
26         }
27         if (prev == s[i]) {
28             break;
29         } else {
30             prev = s[i];
31         }
32     }
33 
34     v.clear();
35     return i == n ? count + 1 : count;
36 }
37 
38 int main()
39 {
40     string s;
41     const int mod = 1009;
42     
43     while (cin >> s) {
44         cout << countSString(s, mod) << endl;
45     }
46     
47     return 0;
48 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3703632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值