mickole

题目:

问题为带通配符的字符串匹配:?可匹配任意字符,*可匹配任意长度的字符。输入匹配成功的次数

例如:输入asdsssasd

           输入asd

           输出1

           输入a?d

           输出2

           输入a?d*

           输出1、

实现代码:递归实现

#include <iostream>
#include <string.h>

using namespace std;
 

//利用递归判断两个字符串是否匹配,从头开始,不考虑字符串是否包含的情况。 
bool is_pipei(char* str, char* t)
{
 
 
     //t到末尾,匹配成功 
     if(\'\0\' == *t)
             return true;
     
     //t为*号        
     if(\'*\' == *t)
     {
            while(\'\0\' != *str)
            {
                       if(is_pipei(str++, t + 1))return true;
            }
     }
 
     //原文到末尾,匹配失败 
     if(\'\0\' == *str)
             return false;



     //相等则比较下一个字符 
     if(\'?\' == *t || *str == *t)
     {
            return is_pipei(str + 1, t + 1);
     }
     
     //不等则匹配失败 
     return false;
} 


//计算匹配成功次数 
int match(char* str, char* t)
{
    int m = strlen(str);
    int count = 0;
    
    for(int i = 0; i < m; i++ )
    {
            if(is_pipei(str + i,t))
                count++;
    }

    return count;    
    
};

int main(void)
{    
    cout<<match("asdsssasd","a*s")<<endl;
    system("PAUSE"); 
}

 

问题二:不带通配符的朴素匹配问题

代码一:最通用的方法:

//成功则返回匹配下表,失败则返回-1 
int pipei(const char *str, const char *p)
{
    int str_len = strlen(str);
    int p_len = strlen(p);

    for(int i = 0; i <= str_len - p_len ; ++i )
    {
        int j;
        for(j = 0; j < p_len; j++)
            if(p[j] != str[i+j])
                break;
        if(j == p_len)
            return i;
        
    }
    
    return -1;
    
}

代码二:采用递归实现:

//t是否是str字串 
bool is_pipei(const char* str, const char* t)
{
     //t到末尾,匹配成功 
     if(\'\0\' == *t)
             return true;    
 
     //原文到末尾,匹配失败 
     if(\'\0\' == *str)
             return false;

     //相等则比较下一个字符 
     if(*str == *t)
            return is_pipei(str + 1, t + 1);
     if(*str != *t)
            return is_pipei(str + 1, t);
}

分类:

技术点:

相关文章: