Skip to content

Commit dcd28c0

Browse files
committed
decode ways
1 parent b036096 commit dcd28c0

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

โ€Ždecode-ways/se6816.javaโ€Ž

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
ย (0)