• + 0 comments

    My Java 8 solution, implementing a simple Dynamic Programming approach, passing all test-cases, for Max Score of 40. The code is fairly self-explanatory, especially with the comments.

        public static String abbreviation(String a, String b) {
            // Write your code here
            int n = a.length(), m = b.length();
    
            if (n < m) {
                return "NO";
            }
    
            // "dp" is the Dynamic Programming based 2-D boolean array
            //     dp[i][j]: boolean indicating whether the first 'i 'characters of 'a' 
            //               can be transformed into the first 'j' characters of 'b'.
            boolean[][] dp = new boolean[n + 1][m + 1];
    
            // Trivial Base Case: First '0' chars of 'a' already same as first '0' chars of 'b'
            dp[0][0] = true;
    
            // Initialize dp[i][0]: for 1 <= i <= n, as:
            // First 'i' characters of 'a' can be transformed into first '0' characters of 'b'
            // purely via the deletion operation, which is permitted only on Lowercase Chars.
            for (int i = 1; i <= n; i++) {
                dp[i][0] = dp[i-1][0] && Character.isLowerCase(a.charAt(i-1));
            }
    
            // Fill the rest of dp[i][j]: for 1 <= i < = n, and for: 1 <= j <= m, as:
            //     (1) IF a[i-1] is Lowercase:
            //           dp[i][j] == (a[i-1] == b[j-1] AND dp[i-1][j-1])
            //     (2) ELSE:
            //           dp[i][j] = (UpperCase(a[i-1]) == b[j-1] AND dp[i-1][j-1]) OR dp[i-1][j]
    
            for (int i = 1; i <= n; i++) {
    
                char aCh = a.charAt(i - 1);
    
                for (int j = 1; j <= m; j++) {
    
                    char bCh = b.charAt(j - 1);
    
                    if (Character.isUpperCase(aCh)) {
    
                        dp[i][j] = ((aCh == bCh) && dp[i-1][j-1]);
    
                    } else {
    
                        boolean canCapitalize = 
                            ((Character.toUpperCase(aCh) == bCh) && dp[i-1][j-1]);
                        boolean canDelete = dp[i-1][j];
                        dp[i][j] = canCapitalize || canDelete;
    
                    }
    
                }
    
            }
    
            return (dp[n][m] ? "YES" : "NO");
        }