微信扫一扫打赏支持

字符串计数

字符串计数

题目描述

求字典序在s1和s2之间的,长度在len1到len2的字符串的个数,结果mod 1000007。

输入描述:

每组数据包涵s1(长度小于100),s2(长度小于100),len1(小于100000),len2(大于len1,小于100000)

输出描述:

输出答案。
示例1

输入

ab ce 1 2

输出

56

 

 

牛客网题解:


首先要搞清楚字典序的意思:即从两个字符串的下标为0开始进行对比,字典序是从左往右进行对比的。
例如ab,abc这样两者之间的字符串个数为aba、abb,而ab、bb两者之间的字符串个数为:ac、ad、ae…az、ba这26个,所以高位的字符串个数要是26的i次幂。
其次,要理解题目的“长度在len1到len2的字符串的个数”,指的是长度在len1的字符串个数、长度在len1+1的字符串个数。。。长度为len2的字符串个数。
例abcde、acede这两个字符串,长度为1到4表示的是长度为1的时候两个字符a、a之间的个数,长度为2的时候两个字符ab、ac之间的个数,长度为3的时候abc、ace两个字符串之间的个数,长度为4:abcd、aced的个数。

所以计算的时候应该以长度作为变量遍历len1到len2之间的字符串个数,最后相加。
 
 
 3 
 4 private static int process(String str1, String str2, int len1, int len2) {
 5         char[] ch1 = str1.toCharArray();
 6         char[] ch2 = str2.toCharArray();
 7         long res = 0;
 8         for (int i = len1; i <= len2; i++) {
 9             char a = ch1[0];
10             char b = ch2[0];
11             res += (long) Math.pow(26, i - 1) * (b - a);
12             long suma = 0;
13             long sumb = 0;
14             for (int j = 1; j < ch1.length; j++)// 找到比ch1剩余字符串小的字符串个数
15             {
16                 suma = suma + (ch1[j] - 'a') * (long) Math.pow(26, i - 1 - j);
17             }
18             for (int j = 1; j < ch2.length; j++)// 找到比ch2剩余字符串小的字符串个数
19             {
20                 sumb = sumb + (ch2[j] - 'a') * (long) Math.pow(26, i - 1 - j);
21             }
22             res = res + sumb - suma;
23         }
24         res--;
25         res= res % 1000007;
26         return (int) res;
27     }

 

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<math.h>
 5 using namespace std;
 6  
 7 int main(){
 8     //根据题中给出的例子,这个字符串只包含小写字母,不然答案就不应该是56了
 9     string s1,s2;
10     int len1,len2;
11     while(cin>>s1>>s2>>len1>>len2){
12         //只包含小写字母的字符串可以看成26进制的数制
13         //将s1和s2补长到len2长度
14         s1.append(len2-s1.size(),'a');
15         s2.append(len2-s2.size(),(char)('z'+1));
16         vector<int> array;
17         for(int i=0;i<len2;i++){
18             array.push_back(s2[i]-s1[i]);
19         }
20         int result = 0;
21         for(int i=len1;i<=len2;i++){
22             for(int k=0;k<i;k++){
23                 result += array[k]*pow(26,i-1-k);
24             }
25         }
26         //所有字符串最后都不包含是s2自身,所以最后要减1;
27         cout<<result-1<<endl;
28     }
29     return 0;
30 }

 

posted @ 2017-10-25 14:05  范仁义  阅读(1278)  评论(0编辑  收藏  举报