Quick actions

cmd+k|ctrl+k

Navigation

Languages

Untitled

Snippet info

Language

Java

Visibility

public

Author

jameeulla3

Created

2024-10-04T04:58:31.064149Z

Updated

2024-10-04T04:58:31.064149Z

public class LongestMatchingSubstring {

    public static int getLongestMatch(String text, String regex) {
        // Split the regex around the wildcard '*'
        String[] parts = regex.split("\\*");
        String prefix = parts[0];
        String suffix = parts[1];
        
        int n = text.length();
        int prefixLength = prefix.length();
        int suffixLength = suffix.length();

        // Find the first position where the prefix matches
        int start = -1;
        for (int i = 0; i <= n - prefixLength; i++) {
            if (text.startsWith(prefix, i)) {
                start = i;
                break;
            }
        }

        // If no valid prefix match, return -1
        if (start == -1) {
            return -1;
        }

        // Find the last position where the suffix matches
        int end = -1;
        for (int i = n - suffixLength; i >= start + prefixLength; i--) {
            if (text.startsWith(suffix, i)) {
                end = i;
                break;
            }
        }

        // If no valid suffix match, return -1
        if (end == -1) {
            return -1;
        }

        // Return the length of the substring between start and end, inclusive
        return end + suffixLength - start;
    }

    public static void main(String[] args) {
        // Example usage
        String text = "debug";
        String regex = "ug*eb";
        
        int result = getLongestMatch(text, regex);
        System.out.println("The length of the longest matching substring: " + result);
    }
}
INFO