Problem · String

Get Longest Match

Learn this problem
MediumAmazonINTERNOA
See Amazon hiring insights

Problem statement

Amazon is building a cutting-edge library for efficient string pattern matching. Your mission is to develop a service that detects the longest continuous segment within a provided string that aligns with a specified pattern.

You are given two inputs: a string sourceStr representing the main text, and a pattern string regexPattern containing one wildcard character (*). This wildcard can stand for any sequence of lowercase English letters, including an empty sequence. The pattern is considered a match if the wildcard can be substituted in a way that makes the pattern identical to a section of sourceStr

For instance, the pattern "abc*bcd" can match substrings like "abcbcd", "abcefgbcd", and "abccbcd", but it won't match "abcbd", "abzbcd", or "abcd".

Your goal is to find the longest matching substring in sourceStr that satisfies the pattern. Return its length, or -1 if no matching substring exists.

Function

getLongestMatch(srcStr: String, regexPattern: String) → int

Complete the function getLongestMatch in the editor below.

getLongestMatch has the following parameters:

  • 1. STRING sourceStr: a string
  • 2. STRING regexPattern: a string
  • Returns

    int: the length of the longest substring that matches the regex, or -1 if there is no such substring.

    🌷 🌿 Credit to Jane and txr 🌿 🌷

    Examples

    Example 1

    srcStr = "hackerrank"regexPattern = "ack*r"return = 6
    The following substrings match regex:
  • "acker", we can replace * with "e" and regex becomes equal to "acker". length = 5
  • "ackerr", we can replace * with "er" and regex becomes equal to "ackerr". length = 6
  • Return the length of the longest matching substring, 6.

    Example 2

    srcStr = "programming"regexPattern = "r*in"return = 9
    "rammin", len = 6. We can replace * with "amm" "rogrammin" len = 9. We can replace * with "ogramm"

    Example 3

    srcStr = "debug"regexPattern = "ug*eb"return = -1
    No substring of text begins with 'u' and ends with 'eb'

    Constraints

  • 1 <= |srcStr|, |regexPattern| <= 10^6
  • text contains lowercase English letters only
  • regex contains lowercase English letters and exactly one wildcard(*) character
  • More Amazon problems

    drafts saved locally
    public int getLongestMatch(String srcStr, String regexPattern) {
      // write your code here
    }
    
    srcStr"hackerrank"
    regexPattern"ack*r"
    expected6
    checking account