|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +public class Geegong { |
| 7 | + |
| 8 | + /** |
| 9 | + * case 1. decodeMap 에 array 의 각 index 별로 디코딩이 가능한 자릿수를 list 로 관리 |
| 10 | + * 후에 decodeMap 을 dfs 로 순회하면서 조합이 가능한 방법을 찾는 방법 |
| 11 | + * 그러나 Time Limit Exceeded 발생ㅠㅠ |
| 12 | + * @param s |
| 13 | + * @return |
| 14 | + */ |
| 15 | + public int numDecodings(String s) { |
| 16 | + Map<Integer, List<Integer>> decodeMap = new HashMap<>(); |
| 17 | + char[] charArr = s.toCharArray(); |
| 18 | + |
| 19 | + int prevVal = -1; |
| 20 | + for (int index=0; index<charArr.length; index++) { |
| 21 | + String str = String.valueOf(charArr[index]); |
| 22 | + int currentVal = Integer.valueOf(str); |
| 23 | + |
| 24 | + if (currentVal == 0 && (prevVal == -1 || prevVal > 2)) { |
| 25 | + // ex) 02xxxx.. , 30xxxx, 1230xxx, 1302xxx |
| 26 | + // there is no way |
| 27 | + return 0; |
| 28 | + } else if (currentVal == 0 && prevVal < 3 && prevVal > 0) { |
| 29 | + appendDigitNumbers(decodeMap, index - 1, 2, true); |
| 30 | + } else if (currentVal > 0) { |
| 31 | + appendDigitNumbers(decodeMap, index, 1, false); |
| 32 | + |
| 33 | + if (prevVal == 2 && currentVal < 7) { |
| 34 | + // for maximum 26 |
| 35 | + appendDigitNumbers(decodeMap, index - 1, 2, false); |
| 36 | + } else if (prevVal > 0 && prevVal < 2) { |
| 37 | + appendDigitNumbers(decodeMap, index - 1, 2, false); |
| 38 | + } |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + prevVal = currentVal; |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + // judge ways |
| 47 | + return dfs(decodeMap, 0); |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + public int dfs(Map<Integer, List<Integer>> decodeMap, int index) { |
| 52 | + // 자릿수 끝이면 끝 |
| 53 | + if (index > decodeMap.keySet().size() - 1) { |
| 54 | + return 1; |
| 55 | + } |
| 56 | + |
| 57 | + int totalWays = 0; |
| 58 | + if (decodeMap.containsKey(index)) { |
| 59 | + List<Integer> waysDigitNumbers = decodeMap.get(index); |
| 60 | + |
| 61 | + for (Integer digit : waysDigitNumbers) { |
| 62 | + totalWays += dfs(decodeMap, index + digit); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return totalWays; |
| 67 | + } |
| 68 | + |
| 69 | + public void appendDigitNumbers(Map<Integer, List<Integer>> decodeMap, int index, int digitNumber, boolean forceNewWays) { |
| 70 | + if (!decodeMap.containsKey(index) || forceNewWays) { |
| 71 | + List<Integer> waysDigitNumber = new ArrayList<>(); |
| 72 | + waysDigitNumber.add(digitNumber); |
| 73 | + decodeMap.put(index, waysDigitNumber); |
| 74 | + } else { |
| 75 | + List<Integer> waysDigitNumber = decodeMap.get(index); |
| 76 | + waysDigitNumber.add(digitNumber); |
| 77 | + decodeMap.put(index, waysDigitNumber); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments