[C++] 数据结构与算法----5.3 匹配字符串 →→→→→进入此内容的聊天室

来自 , 2019-10-06, 写在 C++, 查看 106 次.
URL http://www.code666.cn/view/0189caa5
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. bool match (string p, string s)
  6. {
  7.        
  8.         int i, j, m, n ; bool **d;             
  9.         m=p.length(); n=s.length();
  10.         d=new bool *[m+1] ;
  11.        
  12.         for ( i= 0 ; i<=m;i++) d[i] =new bool [n+1];
  13.         d[0][0]= true ;
  14.        
  15.         for ( j= 1 ; j<=n;j++) d[0][j]= false ;
  16.         for ( i= 1 ; i<=m;i++)
  17.         {
  18.                 if(p[i-1]=='*') d[i][0] =d[i-1][0];
  19.                 else d[i][0]= false ;
  20.         }
  21.         for ( i= 1 ; i<=m;i++)
  22.         {
  23.                 for ( j= 1 ; j<=n;j++)
  24.                         if(p[i-1]=='*')
  25.                                 d[i][j] = d[i-1][j] || d[i][j-1];
  26.                         else if(p[i-1]=='?') d[i][j] =d[i-1][j-1];
  27.                         else d[i][j] =d[i-1][j-1] && p[i-1]==s[j-1];                   
  28.         }
  29.         return d[m][n];
  30. }
  31. int main()
  32. {
  33.     string y="ABCDEF";
  34.         string x="?B*F";
  35.         string s="123456";
  36.         string p="A*5";
  37.         cout<<"模式字符串x:"<<x<<endl<<"待匹配字符串y:"<<y<<endl;
  38.         cout<<"y"<<(match(x,y)?"符合":"不符合")<<"x"<<endl<<endl;
  39.  
  40.         cout<<"模式字符串p:"<<p<<endl<<"待匹配字符串s:"<<s<<endl;
  41.         cout<<"s"<<(match(p,s)?"符合":"不符合")<<"p"<<endl;
  42.         return 0;
  43. }

回复 "数据结构与算法----5.3 匹配字符串"

这儿你可以回复上面这条便签

captcha