字符串计数

来源:互联网 发布:usb网络接口转换器 编辑:程序博客网 时间:2024/06/05 09:49

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

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

先提醒一个坑:什么叫每组数据!!好吧,就是你的大半个程序都要被while(s.hasNext())里……

咳咳……让我们回归程序,这个程序正常想法就是分成三部分:首字母为c1[0],比s1大的;首字母为c2[0],比s2小的;首字母在他们之间的;这种做法完全没问题。

这里我拿出来的是另一种思路,同样三部分,但是却是:首字母为c1[0],比s1小的;首字母为c2[0],比s2小的;首字母在(c1[0], c2[0]]里的;

之所以这么做是因为求 首字母为c1[0],比s1大的 真心麻烦,还不如算比他小的,然后用首字母为c1[0]算出来的数减,然后再减1(s1本身),计算方便,代码简洁,可读性也很好。

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        while (s.hasNext()) {            String str = s.nextLine();            String[] array = str.split(" ");            String s1 = array[0];            String s2 = array[1];            int l1 = Integer.parseInt(array[2]);            int l2 = Integer.parseInt(array[3]);            int res = 0;            long count = 0;            char[] c1 = s1.toCharArray();            char[] c2 = s2.toCharArray();            for(int i=l1; i<=l2; i++) {                //中间部分                count += (long) Math.pow(26, i - 1) * (c2[0] - c1[0]);                //以c1[0]开头,小于s1的                long sum1 = 0;                for(int j=1; j<c1.length; j++) {                    sum1 += (long) Math.pow(26, i - 1 - j) * (c1[j] - 'a');                }                //以c2[0]开头,小于s2的                long sum2 = 0;                for(int j=1; j<c2.length; j++) {                    sum2 += (long) Math.pow(26, i - 1 - j) * (c2[j] - 'a');                }                count = count - sum1 + sum2;            }            count--;            count = count % 1000007;            res = (int)count;            System.out.println(res);        }    }}


0 0
原创粉丝点击