No.010: Regular Expression Matching, no.010matching

Source: Internet
Author: User

No.010: Regular Expression Matching, no.010matching

Question:

Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching shocould cover the entire input string (not partial ).
Some Examples:
IsMatch ("aa", "a") → false
IsMatch ("aa", "aa") → true
IsMatch ("aaa", "aa") → false
IsMatch ("aa", "a *") → true
IsMatch ("aa", ". *") → true
IsMatch ("AB", ". *") → true
IsMatch ("aab", "c * a * B") → true
IsMatch ("aab", ". * a") → false
IsMatch ("aab", ". * AB") → true

Official difficulty:

Hard

Translation:

Matches string regular expressions. special characters "." and "*" are supported "*".

"." Can match any single character.

"*" Can match 0 or more characters before.

The matching algorithm should be able to match all of the following examples, not parts.

Example:

IsMatch ("aa", "a") → false
IsMatch ("aa", "aa") → true
IsMatch ("aaa", "aa") → false
IsMatch ("aa", "a *") → true
IsMatch ("aa", ". *") → true
IsMatch ("AB", ". *") → true
IsMatch ("aab", "c * a * B") → true
IsMatch ("aab", ". * a") → false
IsMatch ("aab", ". * AB") → true

Ideas:

1. Only the matching strings of regular expressions are considered to include only "*" and ".". Other special symbols (including parentheses) are not within the scope of consideration.

2. Start traversal based on the string length to be parsed.

3. If the string to be parsed is still present while the regular string is absent or vice versa, return failure.

4. Starting from the first character, if special characters are not taken into account, the next matching of the string to be parsed will be performed.

5. The special string "." exists separately, and the match passes directly.

6. when the special string "*" appears separately, calculate the length of the previous character in the string to be parsed, the length of the string to be parsed will be skipped in the next calculation (including 0 ).

7. The combination of special strings ". *" can match strings with any length or content. For example, ". *" can match "abhsjksdhak", ". * a" can match "dhaudhjoaidhaida", but cannot match "bdab ".

8. In case of 7, consider traversing the remaining part of the string to be parsed and matching the part after the regular string. For example, "AB. * c. d "and" abctucid ". Check whether" ctucid "matches" c. d "," tucid "matching" c. d "until" d "matches" c. d ". If a successful match exists, true is returned.

Possible difficulties in solving problems:

1. Check the length of the regular string after the parsed string is traversed.

2. ". * "the processing method is written together with any character +" * ", and the return value is a length. Note that a special value is returned after processing ends, so do not affect other operations.

Solution code:

1 private static boolean method (String str, String regularStr) {2 String strWithoutHead = str; 3 String regularStrWithoutHead = regularStr; 4 int alreadyMatchedLength = 0; 5 // The regular String to be processed 6 String regularStrToDeal = null; 7 int strLengthToReduce; 8 while (alreadyMatchedLength <str. length () {9 // because the exit condition is that the length of the parsed string is equal to the original length, 10 // when a loop is completed, make a judgment, the regular expression length is less than 11 if (regularStrWithoutHead. length () = 0) {12 re Turn false; 13} 14 if (regularStrWithoutHead. length ()> 1 & regularStrWithoutHead. substring (1, 2 ). equals ("*") {15 // The second number is "*" case 16 regularStrToDeal = regularStrWithoutHead. substring (0, 2); 17 // take into account ". * "in this case, the entire remaining regular and strings to be processed are passed in 18 strLengthToReduce = matchStarLength (strWithoutHead, regularStrWithoutHead); 19 //". * "special processing, because there is recursion, here is an exit 20 if (strLengthToReduce =-1) {21 return true; 22} else if (strLengt HToReduce =-2) {23 return false; 24} 25} else {26 // single matching condition 27 regularStrToDeal = regularStrWithoutHead. substring (0, 1); 28 if (! SingleStringMatch (strWithoutHead. substring (0, 1), regularStrToDeal) {29 return false; 30} 31 strLengthToReduce = 1; 32} 33 // increase the length of the processed string 34 alreadyMatchedLength + = strLengthToReduce; 35 // remove the header 36 strWithoutHead = str. substring (alreadyMatchedLength); 37 regularStrWithoutHead = regularStrWithoutHead. substring (regularStrToDeal. length (); 38} 39 // to be parsed, but the regular expression still has 40 if (regularStrWithoutHead. length ()> 0) {41 return false; 42} 43 return true; 44} 45 46 // single character matching problem 47 private static boolean singleStringMatch (String str, String regularStr) {48 // special symbol ". "Process 49 if (regularStr. equals (". ") {50 return true; 51} else if (str. equals (regularStr) {52 return true; 53} 54 return false; 55} 56 57 // because "*" will definitely match successfully, return the matching length of the original String 58 // str is not the original String, is the first position where "*" starts matching 59 private static int matchStarLength (String str, String regularString) {60 int length = 0; 61 if (regularString. substring (0, 1 ). equals (". ") {62 // the most annoying point :". * "processing 63 // remove the corresponding regular string first ". * "64 String regularRemain = regularString. substring (2); 65 //". * "do not follow, match all 66 if (regularRemain. equals ("") {67 // return the remaining String Length 68 return str. length (); 69} 70 // recursion 71 for (int I = 0; I <str. length (); I ++) {72 String remain = str. substring (I); 73 // start recursion 74 if (method (remain, regularRemain) {75 // if true appears, 76 return-1 can be matched directly; 77} 78} 79 // none of the remaining values are successful, indicating that the entire request does not match 80 return-2; 81} else {82 // normal character + "*" 83 String regularInUse = regularString. substring (0, 1); 84 for (int I = 0; I <str. length (); I ++) {85 if (regularInUse. equals (str. substring (I, I + 1) {86 length ++; 87} else {88 break; 89} 90} 91} 92 return length; 93}View Code

Test Code address:

Https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/hard/Q010.java

LeetCode address:

Https://leetcode.com/problems/regular-expression-matching/

PS: After writing it, you can find that recursion is directly applied to the remaining strings without repeating the strings to be parsed. This may be a better idea.

PPS: If you have any incorrect or more efficient methods, please leave a message. Thank you!

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.