zoukankan      html  css  js  c++  java
  • 字符串练习——唐纳德与子串 (Easy)

    G1. 唐纳德与子串 (Easy)

    Time limit per test: 1.0 seconds

    Memory limit: 256 megabytes

    子串的定义是在一个字符串中连续出现的一段字符。这里,我们使用 s[lr] 来表示 s 字符串从 l 到 r(闭区间)的子串。在本题中,字符串下标从 0 开始。显然,对于长度为 n 的字符串共有 n(n+1)2 个子串。

    对于一个给定的字符串 s,唐纳德给出 q 次询问,第 i 次询问包括三个参数 li,ri,zi,问在 s[liri] 的所有子串中共有多少个恰好为 zi

    Input

    输入具有如下形式:

    sql1 r1 z1l2 r2 z2lq rq zq

    第一行一个字符串 s

    第二行一个整数 q

    接下来每行:首先两个整数 li,ri (0liri<|s|),然后是一个非空字符串 zi。整数和整数,整数和字符串间以单空格隔开。

    字符串中只会出现 26 个小写英文字母。

    数据规模约定:

    • 对于 Easy 档:1|s|100,q|zi|100
    • 对于 Hard 档:1|s|105,q|zi|105

    Output

    对于每次询问,输出一个整数,表示答案。

    Examples

    input
    thisisagarbagecompetitionhahaha
    5
    0 30 a
    1 5 is
    25 30 hah
    6 12 ag
    7 12 ag
    
    output
    6
    2
    2
    2
    1
    #include "bits/stdc++.h"
    using namespace std;
    int main()
    {
        string s;
        cin >> s;
        int q;
        cin >> q;
        while(q--)
        {
            int l,r;
            string pattern;
            cin >> l >> r >> pattern;
            string s1 = s.substr(l,r-l+1);
            int len = pattern.length();
            int positon = 0;
            int count = 0;
            while(s1 != "")
            {
    //                int s1len = s1.length();
                if(s1.find(pattern)>100000)
                    break;
                positon = s1.find(pattern);
                s1 = s1.substr(positon+1);
                count++;
            }
            cout << count << endl;
        }
    
    
        return 0;
    }

    又是字符串匹配问题,踩坑无数啊!!!

    1:s.find()  如果没找到会返回一个巨大的数,如果你想用这个来判断是否存在子串,不能用一个变量来储存,而是应该直接在if中判断。

    2:s.substr(start,len)  substr 参数第一个是起始位置,第二个是子串长度(不写默认直到最后)。

  • 相关阅读:
    SQL查询设计方案
    [导入]mootools框架【十】mootools深层探讨
    关于阅读技术类图书的思考
    [导入]mootools框架【三】Array篇: 主要方法测试实例
    Google Chrome隐藏的其他功能
    2010年就业最吃香的五大专业详情揭秘
    [导入]mootools框架【四】Function篇: 主要方法解析
    [导入]mootools框架【九】工具类Hash和Color
    [导入]mootools框架【八】Dom篇: Css查询支持之Dom.js
    分页控件入门
  • 原文地址:https://www.cnblogs.com/cunyusup/p/8007056.html
Copyright © 2011-2022 走看看