geekelo / dsa_practice

This repo is maintained just for the purpose of daily data structures and algorithm practice and proficiency
1 stars 0 forks source link

JavaScript pattern matching #11

Open geekelo opened 5 months ago

geekelo commented 5 months ago

Given a string text and a pattern, evaluate if a given text string matches a specified pattern utilizing special characters for pattern matching. The pattern matching should adhere to the following rules. The symbol, full stop, represents any individual character. The symbol, asterisk, indicates zero or more occurrences of a character that appears just before it. Return true if the pattern corresponds exactly to the entire text string. If not, return false. Note, your implementation should be dependent on regular expression or similar convenience libraries. Your implementation should be able to handle all hidden test cases correctly. Example 1, the input text is aa. Pattern is a. Output is false. Explanation, the symbol a does not match the full text aa. Example 2, text is aa, pattern is a. Output, okay, pattern is a asterisk. Output is true. Explanation, the pattern a asterisk can represent aa as asterisk allows for repeating a. Example 3, input ab asterisk dot asterisk. Output is true. Explanation, the pattern dot asterisk can match any sequence of characters. Okay, constraints, one is less than equals text dot length less than equals 20. One is less than equals pattern dot length less than equals 20. Text contains only lowercase English letters. Pattern contains only lowercase English letters, dots and asterisks. It is guaranteed for each appearance of the character asterisk. There will be a previous valid character to match. Okay, and I'll be solving this using JavaScript. Alright.

Image

geekelo commented 5 months ago
function isMatch(text, pattern) {
  if (pattern === "") {
    return text === "";
  }
  console.log({'text': text});
  console.log({'pattern': pattern});

  const firstMatch = text !== "" && (text[0] === pattern[0] || pattern[0] === ".");
    console.log({'firstmatch': firstMatch});

  if (pattern.length >= 2 && pattern[1] === "*") {

    if (firstMatch){
    return isMatch(text.substring(1), pattern)
    } else {
    return isMatch(text, pattern.substring(2));
    }

  } else {
    return firstMatch && isMatch(text.substring(1), pattern.substring(1));
  }
}

// Example usage: console.log(isMatch("abc", "a*bc")); // Output: true