We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
publicstaticStringabbreviation(Stringa,Stringb){// Write your code hereintn=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=newboolean[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(inti=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(inti=1;i<=n;i++){charaCh=a.charAt(i-1);for(intj=1;j<=m;j++){charbCh=b.charAt(j-1);if(Character.isUpperCase(aCh)){dp[i][j]=((aCh==bCh)&&dp[i-1][j-1]);}else{booleancanCapitalize=((Character.toUpperCase(aCh)==bCh)&&dp[i-1][j-1]);booleancanDelete=dp[i-1][j];dp[i][j]=canCapitalize||canDelete;}}}return(dp[n][m]?"YES":"NO");}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Abbreviation
You are viewing a single comment's thread. Return to all 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.