1. Split the regex string into two parts at the '*':
2. Loop through every starting index i in the text:
- Check if the prefix matches the text starting at i.
- If yes, loop through all positions j starting from i + prefix length to text end:
- Check if the suffix matches the text at position j.
- Keep track of maximum length found.
3. After checking all possibilities, return the maximum length.
- If no match found, return -1.
#include <iostream>
using namespace std;
// Function to check if a pattern matches text starting at index i
bool matchesAt(const string &text, const string &pattern, int i) {
if (i + pattern.length() > text.length()) return false;
for (int j = 0; j < pattern.length(); j++) {
if (text[i + j] != pattern[j]) return false;
}
return true;
}
int getLongestMatch(string text, string regex) {
// Step 1: Split regex into prefix and suffix
int star = -1;
for (int i = 0; i < regex.length(); i++) {
if (regex[i] == '*') {
star = i;
break;
}
}
string prefix = "";
string suffix = "";
for (int i = 0; i < star; i++) prefix += regex[i];
for (int i = star + 1; i < regex.length(); i++) suffix += regex[i];
int maxLen = -1;
// Step 2: Loop through all starting positions
for (int i = 0; i < text.length(); i++) {
// Check if prefix matches at i
if (matchesAt(text, prefix, i)) {
// Step 3: Check all possible suffix positions after prefix
for (int j = i + prefix.length(); j <= text.length() - suffix.length(); j++) {
if (matchesAt(text, suffix, j)) {
int len = j + suffix.length() - i;
if (len > maxLen) maxLen = len;
}
}
}
}
return maxLen;
}
int main() {
cout << getLongestMatch("hackerrank", "ack*r") << endl; // 6
cout << getLongestMatch("programming", "r*in") << endl; // 9
cout << getLongestMatch("debug", "ug*eb") << endl; // -1
return 0;
}