|
| 1 | + |
| 2 | +// NOTE: O(n) |
| 3 | +class Solution { |
| 4 | + public int numDecodings(String s) { |
| 5 | + |
| 6 | + char[] cArr = s.toCharArray(); |
| 7 | + int[] decode = new int[cArr.length]; |
| 8 | + |
| 9 | + if((cArr[0] - 48) == 0) { |
| 10 | + return 0; |
| 11 | + } |
| 12 | + |
| 13 | + decode[0] = 1; |
| 14 | + |
| 15 | + for(int i = 1; i < cArr.length; i++) { |
| 16 | + int cur = (int) cArr[i] - 48; |
| 17 | + int prev = (int) cArr[i - 1] - 48; |
| 18 | + |
| 19 | + if(cur == prev && cur == 0) return 0; |
| 20 | + |
| 21 | + String temp = "" + cArr[i - 1] + cArr[i]; |
| 22 | + int tempI = Integer.parseInt(temp); |
| 23 | + |
| 24 | + // NOTE: 아래 if 문 두개가 core logic |
| 25 | + if(cur != 0) { |
| 26 | + decode[i] += decode[i - 1]; |
| 27 | + } |
| 28 | + |
| 29 | + if(tempI >= 10 && tempI <= 26) { |
| 30 | + decode[i] += (i >= 2 ? decode[i - 2] : 1); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return decode[decode.length - 1]; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | + |
| 39 | +class WrongSolution { |
| 40 | + public int numDecodings(String s) { |
| 41 | + |
| 42 | + char[] cArr = s.toCharArray(); |
| 43 | + int[] decode = new int[cArr.length]; |
| 44 | + |
| 45 | + if((cArr[0] - 48) == 0) { |
| 46 | + return 0; |
| 47 | + } |
| 48 | + |
| 49 | + decode[0] = 1; |
| 50 | + |
| 51 | + // 유효한 경우만 판단해서 처리해주면 됐었던 문제.. |
| 52 | + // 어떻게 처리해야할지 모르겠는 분기는 처리하지 않하느니만 못하다...ㅜ |
| 53 | + for(int i = 1; i < cArr.length; i++) { |
| 54 | + int cur = (int) cArr[i] - 48; |
| 55 | + int prev = (int) cArr[i - 1] - 48; |
| 56 | + |
| 57 | + if(cur == prev && cur == 0) return 0; |
| 58 | + |
| 59 | + String temp = "" + cArr[i - 1] + cArr[i]; |
| 60 | + int tempI = Integer.parseInt(temp); |
| 61 | + |
| 62 | + if(cur >= 1 && cur <= 9) { |
| 63 | + decode[i] = decode[i - 1]; |
| 64 | + |
| 65 | + if(prev >= 1 && prev <= 9) { |
| 66 | + if(tempI >= 1 && tempI <= 26) { |
| 67 | + decode[i] = i == 1 ? decode[i - 1] + 1 : decode[i - 1] + decode[i - 2]; |
| 68 | + } |
| 69 | + } else { // 이전값이 0이라 정상적인 디코딩이 안되는 경우.. |
| 70 | + decode[i]--; |
| 71 | + } |
| 72 | + |
| 73 | + } else { // 뒷 숫자와 합쳐져서 유효하게 될 수도 있는경우 |
| 74 | + decode[i] = (tempI >= 1 && tempI <= 26) ? decode[i - 1] : 0; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return decode[decode.length - 1]; |
| 79 | + } |
| 80 | +} |
0 commit comments