|
| 1 | +/** |
| 2 | + HashSet๊ณผ substring์ ์ด์ฉํ์ฌ ๋ฌธ์์ด์ ๋น๊ตํ๋ฉด์ ๊ฐ๋ฅํ ์กฐํฉ์ ์๋ฅผ ๋์ ํ๋ ๋ฐฉ์ |
| 3 | + ๋ฌธ์์ด S ์ ๊ธธ์ด -> N |
| 4 | + ์๊ฐ ๋ณต์ก๋ : O(N^2) |
| 5 | + ๊ณต๊ฐ ๋ณต์ก๋ : O(N) |
| 6 | + */ |
| 7 | +class Solution2 { |
| 8 | + Set<String> numberSet = new HashSet<>(); |
| 9 | + { |
| 10 | + numberSet.addAll(Arrays.asList("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26")); |
| 11 | + } |
| 12 | + public int numDecodings(String s) { |
| 13 | + if(s.length() == 1) return s.charAt(0) == '0' ? 0 : 1; |
| 14 | + |
| 15 | + int[] list = new int[s.length()]; |
| 16 | + list[0] = isImpossibleDecode(s.substring(0,1)) ? 0 : 1; |
| 17 | + list[1] = isImpossibleDecode(s.substring(0,2)) ? 0 : 1; |
| 18 | + list[1] += list[0]==1 && !isImpossibleDecode(s.substring(1,2)) ? 1 : 0; |
| 19 | + |
| 20 | + |
| 21 | + for(int i = 2; i < s.length() ; i++) { |
| 22 | + list[i] += isImpossibleDecode(s.substring(i-1,i+1)) ? 0 : list[i-2]; |
| 23 | + list[i] += isImpossibleDecode(s.substring(i,i+1)) ? 0 : list[i-1]; |
| 24 | + } |
| 25 | + |
| 26 | + return list[s.length()-1]; |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + public boolean isImpossibleDecode(String target) { |
| 31 | + int len = target.length(); |
| 32 | + if(!numberSet.contains(target)) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + return false; |
| 37 | + |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + ์ด์ substring() ์ฐ์ฐ ๋ถ๋ถ ์ต์ ํ |
| 43 | + ์ด์ substring()์ผ๋ก ๋ฌธ์์ด์ ์๋ฅด์ง ์๊ณ , charAt()์ ์ด์ฉํ์ฌ ์ง์ ์ฐ์ฐํ์ฌ ์กฐํฉ์ ์๋ฅผ ๋์ ์ํค๋ ๋ฐฉ์ |
| 44 | + ๋ฌธ์์ด S ์ ๊ธธ์ด -> N |
| 45 | + ์๊ฐ ๋ณต์ก๋ : O(N) |
| 46 | + ๊ณต๊ฐ ๋ณต์ก๋ : O(N) |
| 47 | + */ |
| 48 | +class Solution { |
| 49 | + |
| 50 | + public int numDecodings(String s) { |
| 51 | + if(s.length() == 1) return s.charAt(0) == '0' ? 0 : 1; |
| 52 | + |
| 53 | + int[] list = new int[s.length()]; |
| 54 | + list[0] = s.charAt(0) == '0' ? 0 : 1; |
| 55 | + int target = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); |
| 56 | + list[1] = (target >= 10) && (target <= 26) ? 1 : 0; |
| 57 | + list[1] += list[0]==1 && s.charAt(1) != '0' ? 1 : 0; |
| 58 | + |
| 59 | + |
| 60 | + for(int i = 2; i < s.length() ; i++) { |
| 61 | + target = (s.charAt(i-1) - '0') * 10 + (s.charAt(i) - '0'); |
| 62 | + list[i] += (target >= 10) && (target <= 26) ? list[i-2] : 0; |
| 63 | + list[i] += s.charAt(i) != '0' ? list[i-1] : 0; |
| 64 | + } |
| 65 | + |
| 66 | + return list[s.length()-1]; |
| 67 | + |
| 68 | + } |
| 69 | +} |
0 commit comments