一、题目描述
- 字典序在ab、ce之间的且长度为1的字符串是
b、c- 字典序在ab、ce之间的且长度为2的字符串是
ac、ad、ae…az
ba、bb、bc…bz
ca、cb、cc、cd总数是 2 + 24 + 26 + 4 = 56
二、分析题目
- 字典序在ab、ce之间的且长度为2的字符串如何求呢?
将字母看作是二十六进制的
c - a = 2
e - b = 3
3*26^0 + 2*26^1 - 1
(-1是因为结果包含ce) =54- 字典序在ab、ce之间的且长度为1的字符串如何求呢?
c - a = 2
2*26^0
=2- 得出如何求字典序在s1、s2之间的不同长度的字符串的数目
- 如何求字典序在s1、s2之间的且长度为len(len > str.lenth())的字符串的?
将s1和s2补位,补位至其长度为 len
s1用'a'
补位
s2用'z' + 1
补位
三、解决方法
- 将s1、s2补位至 len2(因为len2 > len1),s1用 ‘a’ 补位,s2用 ‘z’ + 1 补位
- 将新的s1、s2的每一位相减(s2 - s1),保存到一个数组(array)中
- 计算每个长度的字符串数目
从长度len1(i = len1-1)开始 ------------ 长度len2(i = len2-1)结束
对于一个长度为 i + 1的字符串,用 j 遍历array[0] ----> array[i];此长度的字符串数目为 array[j] * 26 ^ (i - j)- 不同长度字符串数目的加和即为最后的结果
- 最后 - 1,因为包含 (s2)
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
StringBuilder s1 = new StringBuilder(scanner.next());
StringBuilder s2 = new StringBuilder(scanner.next());
int len1 = scanner.nextInt();
int len2 = scanner.nextInt();
for (int i = s1.length(); i < len2; i++) {
s1.append('a');
}
for (int i = s2.length(); i < len2; i++) {
s2.append('z' + 1);
}
int[] array = new int[len2];
for (int i = 0; i < len2; i++) {
array[i] = s2.charAt(i) - s1.charAt(i);
}
int result = 0;
// 不同长度的字符串 一个有多少种
for (int i = len1 - 1; i < len2; i++) {
// 长度为 i + 1 的字符串有多少种
for (int j = 0; j <= i; j++) {
result += array[j] * Math.pow(26, i - j);
}
}
// 包含s2,所以要 -1
System.out.println((result - 1) % 1000007);
}
}
}
红瓦绿树,碧海蓝天