Advertisement
GokulDeep

DP

Aug 25th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.81 KB | Source Code | 0 0
  1. package com.gokul.demo.InProgress.DP;
  2. import java.util.Arrays;
  3. public class DynamicProbs {
  4. public static void main(String[] args) {
  5. System.out.println(numDecodings("2101"));
  6. }
  7. public static int numDecodings(String s) {
  8. int[] arr = new int[s.length()];
  9. Arrays.fill(arr, -1);
  10. return countOfDecodings(s, 0, arr);
  11. }
  12. private static int countOfDecodings(String s, int i, int[] arr) {
  13. if (i == s.length()) {
  14. return 1;
  15. }
  16. if (arr[i] != -1) {
  17. return arr[i];
  18. }
  19. arr[i] = 0;
  20. if (isValid(s.charAt(i) - '0', 1)) {
  21. arr[i] += countOfDecodings(s, i + 1, arr);
  22. }
  23. if (i > 0 && isValid((s.charAt(i - 1) - '0') * 10 + s.charAt(i) - '0', 2)) {
  24. arr[i] += countOfDecodings(s, i + 2, arr);
  25. }
  26. return arr[i];
  27. }
  28. private static boolean isValid(int c, int l) {
  29. if (l == 1) {
  30. return c >= 1 && c <= 9;
  31. }
  32. return c >= 10 && c <= 26;
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement