leetcode-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.
原题地址

首尾对比,只有五种匹配的方式:0-0, 1-1, 8-8, 6-9, 9-6。把这些存入hash table会方便许多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool isStrobogrammatic(string num) {
int p_1 = 0;
int p_2 = num.size() - 1;
unordered_map<char, char> hash;
hash['0'] = '0';
hash['1'] = '1';
hash['8'] = '8';
hash['6'] = '9';
hash['9'] = '6';
while (p_2 >= p_1) {
if (hash.count(num[p_1]) == 0 || hash[num[p_1]] != num[p_2]) {
return false;
}
p_1++;
p_2--;
}
return true;
}