Leetcode Dynamic Programming Topic Summary "Continuous Update"

Source: Internet
Author: User

The following question numbers are Leetcode, which makes it easy to view the original problem.

Ten. Regular Expression Matching

Test instructions: Implements a regular Match of strings, containing '. ' and ' * '. '. ' matches any one character, "*" matches 0 or more characters prior to ' * '.

Example

false IsMatch (trueIsMatch (falseIsMatch (trueisMatch ( true IsMatch (trueisMatch (true

Idea: Input string s[0...m] and P[0...N]

F[I][J] for s[0..i-1] and p[0..j-1] matches, we need to determine if s and p match, that is, the value of F[m][n] is true, so we want to update the value of F[i][j].

Update ideas as follows:

1, if p[j-1]!= ' * ', f[i][j] = f[i-1][j-1] & (S[i-1]==p[j-1] | | p[j-1]== '. ')

2, if p[j-1]== ' * ', see ' * ' match how many characters, that is to match how many p[j-2].

If ' * ' matches 0 characters, at this time, p[0...j-1]==p[0...j-3],f[i][j]=f[i][j-2];

If ' * ' matches 1 characters, at this time, p[0...j-1]==p[0...j-2],f[i][j]=f[i][j-1];

If ' * ' matches multiple characters, at this time, p[0...j-1]=={p[0:j-2], p[j-2], ..., p[j-2]},f[i][j]= (s[i-1]==p[j-2] | | p[j-2]== '. ') & F[i-1][j]

 Public BooleanIsMatch (String s, String p) {intm =s.length (); intn =p.length (); Boolean[] f =New Boolean[M+1] [N+1]; f[0][0] =true;  for(inti = 0; I <= m; i++)        {             for(intj = 1; J <= N; J + +)            {                if(P.charat (j-1)! = ' * ') {F[i][j]= I>0 && f[i-1][j-1] && (S.charat (i-1) ==p.charat (j-1) | | P.charat (j-1) = = '. '); }                Else{F[i][j]= (J>1&&f[i][j-2]) | | (i>0&& (S.charat (i-1) ==p.charat (j-2) | | P.charat (j-2) = = '. ') &&f[i-1][j]); }            }        }                returnF[m][n]; }
View Code

Leetcode Dynamic Programming Topic Summary "Continuous Update"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.