My code:
public class Solution {
public boolean isStrobogrammatic(String num) {
if (num == null || num.length() == 0) {
return true;
}
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('6', '9');
map.put('9', '6');
map.put('1', '1');
map.put('0', '0');
map.put('8', '8');
StringBuilder sb = new StringBuilder();
for (int i = 0; i < num.length(); i++) {
char curr = num.charAt(i);
if (!map.containsKey(curr)) {
return false;
}
else {
sb.append(map.get(curr));
}
}
return sb.reverse().toString().equals(num);
}
}
比较简单的题。
可以再优化。hashmap改用array,循环改用双指针。
My code:
public class Solution {
public boolean isStrobogrammatic(String num) {
if (num == null || num.length() == 0) {
return true;
}
int[] map = new int[10];
Arrays.fill(map, -1);
map[0] = 0;
map[1] = 1;
map[6] = 9;
map[8] = 8;
map[9] = 6;
int begin = 0;
int end = num.length() - 1;
while (begin <= end) {
char c1 = num.charAt(begin);
char c2 = num.charAt(end);
if (map[c1 - '0'] != c2 - '0') {
return false;
}
begin++;
end--;
}
return true;
}
}
reference:
https://discuss.leetcode.com/topic/55075/0-ms-array-based-java-solution-easy-to-understand
Anyway, Good luck, Richardo! — 09/22/2016