forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_246.java
80 lines (73 loc) · 2.46 KB
/
_246.java
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 246. Strobogrammatic Number
*
* A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
* Write a function to determine if a number is strobogrammatic. The number is represented as a string.
* For example, the numbers "69", "88", and "818" are all strobogrammatic.
*/
public class _246 {
public static class Solution1 {
public boolean isStrobogrammatic(String num) {
int i = 0;
int j = num.length() - 1;
Map<Character, Character> map = new HashMap();
map.put('8', '8');
map.put('1', '1');
map.put('0', '0');
if (j == 0) {
return map.containsKey(num.charAt(i));
}
map.put('9', '6');
map.put('6', '9');
while (i < j) {
if (!map.containsKey(num.charAt(i)) || !map.containsKey(num.charAt(j))) {
return false;
}
if (map.get(num.charAt(i)) != num.charAt(j)) {
return false;
}
i++;
j--;
}
return map.containsKey(num.charAt(i));
}
}
public static class Solution2 {
public boolean isStrobogrammatic(String num) {
Set<Character> set = new HashSet();
set.add('0');
set.add('1');
set.add('6');
set.add('8');
set.add('9');
char[] nums = num.toCharArray();
int i = 0;
int j = num.length() - 1;
while (i <= j) {
if (!set.contains(nums[i]) || !set.contains(nums[j])) {
return false;
}
if (nums[i] == '6' && nums[j] != '9') {
return false;
} else if (nums[i] == '9' && nums[j] != '6') {
return false;
} else if (nums[i] == '1' && nums[j] != '1') {
return false;
} else if (nums[i] == '8' && nums[j] != '8') {
return false;
} else if (nums[i] == '0' && nums[j] != '0') {
return false;
} else {
i++;
j--;
}
}
return true;
}
}
}