FastPrepFastPrep
Problem Brief

Get Longest Match

INTERNOA
See Amazon online assessment and hiring insights

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 Description

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 🌿 🌷

    1Example 1

    Input
    srcStr = "hackerrank", regexPattern = "ack*r"
    Output
    6
    Explanation
    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.

    2Example 2

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

    3Example 3

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

    Constraints

    Limits and guarantees your solution can rely on.

  • 1 <= |srcStr|, |regexPattern| <= 10^6
  • text contains lowercase English letters only
  • regex contains lowercase English letters and exactly one wildcard(*) character
  • public int getLongestMatch(String srcStr, String regexPattern) {
      // write your code here
    }
    
    Input

    srcStr

    "hackerrank"

    regexPattern

    "ack*r"

    Output

    6

    Sign in to submit your solution.