Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public boolean isMatch(String s, String p) {
- if(p.isEmpty() && s.isEmpty()) {
- return true;
- }
- if(p.isEmpty() && !s.isEmpty()) {
- return false;
- }
- char pChar = p.charAt(0);
- boolean isWildcard = false;
- if(p.length() > 1) {
- isWildcard = p.charAt(1) == '*';
- }
- if(pChar == '.') {
- return validateDot(isWildcard, s, p);
- } else if (pChar >= 'a' && pChar <= 'z') {
- return validateDigit(pChar, isWildcard, s, p);
- } else {
- return false;
- }
- }
- private boolean validateDigit(char c, boolean isWildcard, String s, String p) {
- if(!s.isEmpty()) {
- if (c == s.charAt(0)) {
- int sumChars = sumSequentialChars(c, s);
- if (!isWildcard) {
- return isMatch(s.substring(1), p.substring(1));
- } else {
- return isMatch(s, p.substring(2)) || isMatch(s.substring(sumChars), p.substring(2)) || isMatch(s.substring(1), p);
- }
- }
- if (c != s.charAt(0) && isWildcard) {
- return isMatch(s, p.substring(2));
- }
- } else if(isWildcard) {
- return isMatch(s, p.substring(2));
- }
- return false;
- }
- private boolean validateDot(boolean isWildcard, String s, String p) {
- if(s.isEmpty()) {
- if(!isWildcard) {
- return false;
- }
- }
- if(s.isEmpty()) {
- return isMatch(s, p.substring(2));
- }
- if(!isWildcard) {
- return isMatch(s.substring(1), p.substring(1));
- } else {
- int sumChars = sumSequentialChars(s.charAt(0), s);
- return isMatch(s, p.substring(2)) || isMatch(s.substring(sumChars), p.substring(2))
- || isMatch(s.substring(1), p);
- }
- }
- private int sumSequentialChars(char c, String s) {
- int res = 0;
- while(res < s.length() && c == s.charAt(res)) {
- res++;
- }
- return res;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement