forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrobogrammaticNumber.java
57 lines (48 loc) · 1.87 KB
/
StrobogrammaticNumber.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
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**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 StrobogrammaticNumber {
public boolean isStrobogrammatic_map(String num) {
int i = 0, 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 boolean isStrobogrammatic_set(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, 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;
}
}