博客
关于我
CSDN编程竞赛 ——— 第二十一期
阅读量:798 次
发布时间:2023-04-03

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

要解决这个问题,我们需要找到所有以给定字符串 T 为前缀的单词,并按字典序升序输出。以下是详细的解决方案:

方法思路

  • 输入处理:首先读取输入数据,包括单词数量 N 和接下来的 N 个单词,以及字符串 T。
  • 前缀判断:定义一个辅助函数来判断一个字符串是否以 T 为前缀。这个函数会逐个字符比较,如果所有 T 的字符都在目标字符串中依次出现,则返回 true。
  • 筛选符合条件的单词:遍历所有单词,使用辅助函数筛选出以 T 为前缀的单词。
  • 排序:将筛选出的单词按字典序排序。
  • 输出结果:逐行输出排序后的单词。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;bool isPrefix(const string& str, const string& pre) { if (str.size() < pre.size()) return false; size_t i = 0; while (i < pre.size() && str[i] == pre[i]) { i++; } return i == pre.size();}int main() { int N; cin >> N; vector
    words; for (int i = 0; i < N; ++i) { string word; cin >> word; words.push_back(word); } string T; cin >> T; vector
    result; for (const string& word : words) { if (isPrefix(word, T)) { result.push_back(word); } } sort(result.begin(), result.end()); for (const string& word : result) { cout << word << endl; } return 0;}

    代码解释

  • 输入处理:读取单词数量 N 和每个单词,存储在向量 words 中。读取字符串 T。
  • 前缀判断函数:函数 isPrefix 检查字符串 str 是否以 pre 为前缀。通过逐个字符比较,确保 pre 的所有字符都在 str 中依次出现。
  • 筛选和排序:遍历所有单词,筛选出以 T 为前缀的单词,并存储在 result 向量中。使用 std::sort 对结果进行字典序排序。
  • 输出结果:逐行输出排序后的单词。
  • 这个方法确保了我们能够高效且准确地找到所有符合条件的单词,并按要求输出。

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

    你可能感兴趣的文章
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    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:
    查看>>
    org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>