Regular Expression Matching topic description
Please implement a function to match the include '. ' And the regular expression of ' * '. The characters in the pattern '. ' Represents any character, and ' * ' means that the character preceding it can appear any time (0 times). In the subject, the match refers to all characters of the string that match the entire pattern. For example, the string "AAA" matches the pattern "a.a" and "ab*ac*a", but does not match "aa.a" and "Ab*a"
Ideas
- When encountering '. ' When any character matches, good handling
- When encountering ' * ', there are three possibilities:
- Appears 0 times, does not match
- Appear once, match only once
- Match multiple times
- This is a recursive process.
Code
PublicClassSolution {PublicBoolean Match (Char[]StrChar[] pattern) {Boolean result =Falseif (str = =null | | Pattern = =NULL) {return result; } result = Matchcore (Str0, pattern,0);return result; }PublicBoolean Matchcore (Char[]Strint STRP,Char[] pattern,int PatP) {if (STRP = =Str.length && PatP = = pattern.length) {ReturnTrue }if (STRP <Str.length && PatP = = pattern.length)) {ReturnFalse }if ((PatP +1 < Pattern.length) && PATTERN[PATP +1] = =‘*‘) {if (STRP <Str.length &&STR[STRP] = = PATTERN[PATP]) | | (PATTERN[PATP] = ='. ' && STRP <Str.length)) {Return Matchcore (STR, STRP +1, pattern, PatP +2) | | Matchcore (STR, STRP, pattern, PatP +2) | | Matchcore (STR, STRP +1, pattern, PatP);//match //match 0 times //match multiple} else {return matchcore (str, StrP, pattern, PatP + 2); //matches 0 Times}} if ((STRP < str.length && PATTERN[PATP] = = STR[STRP]) | | (PATTERN[PATP] = = "&& STRP < str.length)) {return matchcore (str, STRP + 1, pattern, PatP + 1); //match once} return false;}
Regular expression matching-Sword point offer