• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
字符串练习——唐纳德与子串 (Easy)
G1. 唐纳德与子串 (Easy)

Time limit per test: 1.0 seconds

Memory limit: 256 megabytes

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

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

Input

输入具有如下形式:

sql1 r1 z1l2 r2 z2⋮lq rq zq

第一行一个字符串 s。

第二行一个整数 q。

接下来每行:首先两个整数 li,ri (0≤li≤ri<|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 参数第一个是起始位置,第二个是子串长度(不写默认直到最后)。

posted on 2017-12-08 20:42  村雨sup  阅读(297)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3