博客
关于我
PAT——1040. 有几个PAT
阅读量:463 次
发布时间:2019-03-06

本文共 1262 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要计算给定字符串中包含多少个“PAT”序列。每个“PAT”序列中的字母P、A、T必须按顺序出现,但不需要连续。

方法思路

我们可以通过从左到右遍历字符串的方式来高效地计算满足条件的“PAT”序列的数量。具体步骤如下:

  • 维护变量:我们需要三个变量来跟踪当前遇到的P的数量、P和A组合的数量以及最终的“PAT”序列的数量。
  • 遍历字符串:从左到右遍历每个字符:
    • 如果遇到P,增加P的计数。
    • 如果遇到A,增加P和A组合的计数。
    • 如果遇到T,则增加最终的“PAT”序列计数。
  • 结果处理:由于结果可能非常大,我们对结果取模1000000007。
  • 这种方法的时间复杂度是O(n),适用于长度很大的字符串。

    解决代码

    public class basicalLevel1040howManyPat {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        char[] pat = in.nextLine().toCharArray();        int len = pat.length;        int pCount = 0, paCount = 0, result = 0;        for (int i = 0; i < len; i++) {            char c = pat[i];            if (c == 'P') {                pCount++;            } else if (c == 'A') {                paCount += pCount;            } else if (c == 'T') {                result += paCount;                // 取模操作                if (result >= 1000000007) {                    result %= 1000000007;                }            }        }        // 在最后,确保结果取模        result %= 1000000007;        System.out.println(result);        in.close();    }}

    代码解释

    • 输入读取:使用Scanner读取输入字符串并转换为字符数组。
    • 变量初始化pCount记录遇到的P的数量,paCount记录遇到的P和A组合的数量,result记录最终的“PAT”序列数量。
    • 遍历字符串:逐个字符处理,更新相应的计数。
    • 结果输出:对结果取模并输出。

    这种方法确保了在O(n)时间内高效地计算满足条件的“PAT”序列数量,适用于大规模输入。

    转载地址:http://vjnbz.baihongyu.com/

    你可能感兴趣的文章
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>