String regular expression matching byte beat Kong R & D program of the original title

Loaded to: https: //segmentfault.com/a/1190000016326888 utm_source = tag-newest?

Subject description:

Given a string (s) and a character pattern (p). Implementation supports '' and '*' in the regular expression matching.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.
Matching should cover the entire string (s), rather than part of the string.
Description:

s may be empty, and only lowercase letters az from the.
p may be empty and contain only lowercase letters from az, and characters. and *.
Example 1:

Input:
S = "AA"
P = "A"
Output: false
interpretation: "a" can not match the entire string "aa".
Example 2:

Input:
S = "AA"
P = "A *"
Output: true
interpretation: '*' for zero or more matches of the front elements, i.e., match 'a'. Thus, repeating 'a' time, the string may be changed to "aa".
Example 3:

Input:
S = "ab &"
P = "*."
Output: true
explained: ". *" Denotes zero or more matches ( '*') of any character ( '.').
Example 4:

Input:
S = "AAB"
P = "C * A * B"
Output: true
interpretation: 'c' may not be repeated, 'a' may be repeated once. So it can match the string "aab".
Example 5:

Input:
S = "Mississippi"
P = "MIS * IS * P *."
Output: false

Method II
after only need to pay attention to a character is a *,
the first character is determined direct comparison, when the second character is a *, there are two cases

0 matches, the pattern 2 directly jump back
one character matches a string of jump back
not matching * can then direct comparison

 

code show as below:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 class Sloution{
 5 public:
 6     bool isMatch(string s,string p){
 7         if(p.empty())return s.empty();
 8         bool firstMatch=!s.empty()&&(s[0]==p[0]||p[0]=='.');
 9         if(p.size()>1 && p[1]=='*')
10             return isMatch(s,p.substr(2))||(firstMatch&&isMatch(s.substr(1),p));
11         else
12             return firstMatch && isMatch(s.substr(1),p.substr(1));
13     }
14 };
15 int main(){
16     string s;
17     string p;
18     int n;
19     cin>>n;
20     while(n--){
21     cout<<"Enter the original character s, and matching characters P: " << endl;
 22 is      CIN S >> >> P;
 23 is      SLOUTION Slo;
 24      COUT << << slo.isMatch the boolalpha (s, P) << endl;
 25      }
 26 is      return  0 ;
 27 }

 

Guess you like

Origin www.cnblogs.com/yichengming/p/11129926.html