Untitled

Run Settings
LanguageJava
Language Version
Run Command
public class LongestSubstringMatch { public static void main(String[] args) { // Test cases String text1 = "hackerrank"; String regex1 = "ack*r"; System.out.println(getLongestMatch(text1, regex1)); // Output: 6 String text2 = "programming"; String regex2 = "r*in"; System.out.println(getLongestMatch(text2, regex2)); // Output: 6 String text3 = "debug"; String regex3 = "ug*eb"; System.out.println(getLongestMatch(text3, regex3)); // Output: -1 } // public static int getLongestMatch(String text, String regex) { // // Split the regex into parts before and after the wildcard character '*' // String[] parts = regex.split("\\*"); // if (parts.length != 2) { // return -1; // Invalid regex format // } // String prefix = parts[0]; // String suffix = parts[1]; // int maxLen = -1; // // Traverse through the text and find substrings that match the regex // for (int i = 0; i <= text.length() - prefix.length(); i++) { // if (text.startsWith(prefix, i)) { // for (int j = i + prefix.length(); j <= text.length(); j++) { // if (text.startsWith(suffix, j)) { // maxLen = Math.max(maxLen, j - i + suffix.length()); // } // } // } // } // return maxLen; // } public static int getLongestMatch(String text, String regex) { String[] parts = regex.split("\\*"); if (parts.length != 2) { return -1; } String prefix = parts[0]; String suffix = parts[1]; int maxLen = -1; int prefixLen = prefix.length(); int suffixLen = suffix.length(); int textLen = text.length(); int prefixIndex = 0; int suffixIndex = textLen - suffixLen; while (prefixIndex <= textLen - prefixLen) { if (text.startsWith(prefix, prefixIndex)) { while (suffixIndex >= prefixIndex + prefixLen) { if (text.startsWith(suffix, suffixIndex)) { int currentMatchLength = suffixIndex + suffixLen - prefixIndex; maxLen = Math.max(maxLen, currentMatchLength); break; // Found a suffix, no need to check further } suffixIndex--; } suffixIndex = textLen - suffixLen; } prefixIndex++; } return maxLen; } }
Editor Settings
Theme
Key bindings
Full width
Lines