zoukankan      html  css  js  c++  java
  • hdu---2087---剪花布条

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087

    这题水的不要不要的,各种数据都能过,醉醉的

    写他的目的是在KMP专题上随时都要充实自己,又长知识了。

    kmp算法完成的任务是:给定两个字符串O和f,长度分别为n和m,判断f是否在O中出现,如果出现则返回出现的位置。

    常规方法是遍历a的每一个位置,然后从该位置开始和b进行匹配,但是这种方法的

    复杂度是O(nm)。kmp算法通过一个O(m)的预处理,使匹配的复杂度降为O(n+m)。

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <cmath>
    #include<vector>
    #include<queue>
    #include<algorithm>
    
    using namespace std;
    typedef long long LL;
    
    const int maxn=1005;
    const int INF=0x3f3f3f3f;
    
    char s1[maxn], s2[maxn];
    
    int main()
    {
        while(scanf("%s", s1), strcmp(s1, "#"))
        {
            scanf("%s", s2);
            int len1=strlen(s1);
            int len2=strlen(s2);
    
            if(len1<len2)
            {
                printf("0
    ");
                continue;
            }
    
            int ans=0, f=1;
            for(int i=0; i<len1; i++)
            {
                if(s1[i]==s2[0])
                {
                    for(int j=1; j<len2; j++)
                    {
                        i++;
                        if(s1[i]!=s2[j])
                        {
                            f=0;
                            break;
                        }
                    }
    
                    if(f)
                        ans++;
                    else
                        f=1;
                }
            }
            printf("%d
    ", ans);
        }
        return 0;
    }

    用指针解决

    直接调用库函数strstr()。

    strstr 语法:

    #include <string.h>

    char *strstr( const char *str1, const char *str2 );

    功能:函数返回一个指针,它指向字符串str2 首次出现于字符串str1中的位置,如果没有找到,返回NULL。

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <cmath>
    #include<vector>
    #include<queue>
    #include<algorithm>
    
    using namespace std;
    typedef long long LL;
    
    const int maxn=1005;
    const int INF=0x3f3f3f3f;
    
    char s1[maxn], s2[maxn];
    
    int main()
    {
        while(scanf("%s", s1), strcmp(s1, "#"))
        {
            scanf("%s", s2);
            char *p;
            int len=strlen(s2);
            int ans=0;
    
            for(p=s1; p=strstr(p, s2); ans++, p+=len);
            printf("%d
    ", ans);
        }
        return 0;
    }
  • 相关阅读:
    docker配置国内加速器
    pwm原理与stm32控制
    【C语言】赋值表达式自增自减逗号表达式
    linux下利用paho.mqtt.c进行mqtt开发 #c编程
    linux下tcp #c编程
    windows下的linux子系统虚拟串口的使用
    linux下搭建mqtt服务器(mosquitto)
    linux下paho.mqtt.c下载安装
    树莓派&mysql数据库
    vscode+mysql数据库编程
  • 原文地址:https://www.cnblogs.com/w-y-1/p/5781972.html
Copyright © 2011-2022 走看看