博客
关于我
PAT-乙级-1040 有几个PAT
阅读量:795 次
发布时间:2023-02-26

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

为了解决这个问题,我们需要计算给定字符串中能形成多少个" PAT "。这里的" PAT "并非连续的三个字符,而是三个字符分别在三个不同的位置上。

方法思路

为了高效地解决这个问题,我们可以采用以下方法:

  • 预处理后缀计数:我们首先计算每个位置后面有多少个'T'。这可以通过从右到左遍历字符串来实现。
  • 预处理前缀计数:然后我们计算每个位置前面有多少个'P'。这可以通过从左到右遍历字符串来实现。
  • 计算总数:对于每个位置,如果该位置是'A',我们计算前面有多少个'P'和后面有多少个'T',然后将这些组合起来,计算总数。
  • 这种方法的时间复杂度是O(n),适合处理长度为10^5的字符串。

    解决代码

    s = input().strip()n = len(s)MOD = 10**9 + 7# 预处理count_T数组:count_T[i]表示从i后面(包括i+1)到末尾的T的数量count_T = [0] * (n + 1)for i in range(n-1, -1, -1):    if s[i] == 'T':        count_T[i] = count_T[i+1] + 1    else:        count_T[i] = count_T[i+1]# 预处理count_P数组:count_P[i]表示前面(包括0到i-1)有多少个Pcount_P = [0] * (n + 1)for i in range(n):    count_P[i+1] = count_P[i] + (1 if s[i] == 'P' else 0)# 计算结果res = 0for j in range(n):    if s[j] == 'A':        res = (res + count_P[j] * count_T[j+1]) % MODprint(res % MOD)

    代码解释

  • 预处理count_T数组:从右到左遍历字符串,计算每个位置后面有多少个'T'。这帮助我们快速确定每个'A'后面有多少个'T'。
  • 预处理count_P数组:从左到右遍历字符串,计算每个位置前面有多少个'P'。这帮助我们快速确定每个'A'前面有多少个'P'。
  • 计算总数:遍历字符串,对于每个'A',计算前面有多少个'P'和后面有多少个'T',然后将这些组合起来,累加得到结果。
  • 这种方法确保了我们在O(n)时间复杂度内解决问题,适用于大规模输入。

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

    你可能感兴趣的文章
    ORCHARD 是什么?
    查看>>
    Struts2中使用Session的两种方法
    查看>>
    order by rand()
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>