Leetcode -- Regular Expression matching

Source: Internet
Author: User

Implement Regular Expression matching with support'.'And'*'.

'. 'Matches any single character.' * 'matches zero or more of the preceding element. The matching shoshould coverEntireInput string (not partial ). the function prototype shoshould be: bool ismatch (const char * s, const char * P) some examples: ismatch ("AA", "A") → falseismatch ("AA ", "AA") → trueismatch ("AAA", "AA") → falseismatch ("AA", "A *") → trueismatch ("AA ",". * ") → trueismatch (" AB ",". * ") → trueismatch (" AAB "," C * a * B ") → true
Implement regular expressions that support '.' and.

'.' Matches any single character.

'*' Matches 0 or multiple forward elements.

Use recursion for determination. In general, there are two possible cases: one is starting with '*', and the other is not.

Public class regularexpressionmatching {public static void main (string [] ARGs) {system. out. println (ismatch ("AA", "A"); system. out. println (ismatch ("AA", "AA"); system. out. println (ismatch ("AAA", "AA"); system. out. println (ismatch ("AA", "A *"); system. out. println (ismatch ("AA ",". * "); system. out. println (ismatch ("AB ",". * "); system. out. println (ismatch ("AAB", "C * a * B");} public static Boolean ismatch (string s, String p) {If (P. length () = 0) return S. length () = 0; If (P. length () = 1 | P. charat (1 )! = '*') {If (S. Length () <1 | (P. charat (0 )! = '.' & S. charat (0 )! = P. charat (0) return false; return ismatch (S. substring (1), p. substring (1);} else {int I =-1; while (I <S. length () & (I <0 | P. charat (0) = '. '| P. charat (0) = S. charat (I) {If (ismatch (S. substring (I + 1), p. substring (2) return true; I ++;} return false ;}}}

reference: The http://www.programcreek.com/2012/12/leetcode-regular-expression-matching-in-java/

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.