[Leetcode] 246. Strobogrammatic Number 解题报告
2017-06-30 14:51
344 查看
题目:
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-9中有五个数字满足这种“镜像对称”,所以我们将它们放在一个哈希表中,然后遍历num中的前一半字符(包括最中间的字符),一旦发现某字符不在哈希表中,或者虽然是,但是在后面的对应位置上的字符不是它的“镜像对称”字符,就返回false。如果检查完所有的字符都没有问题,则返回true。
代码:
class Solution {
public:
bool isStrobogrammatic(string num) {
unordered_map<char, char> hash;
hash['0'] = '0';
hash['1'] = '1';
hash['8'] = '8';
hash['6'] = '9';
hash['9'] = '6';
int length = num.length();
for(int i = 0; i < (length + 1) / 2; ++i) {
if(hash.count(num[i]) == 0 || hash[num[i]] != num[length - 1 - i]) {
return false;
}
}
return true;
}
};
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-9中有五个数字满足这种“镜像对称”,所以我们将它们放在一个哈希表中,然后遍历num中的前一半字符(包括最中间的字符),一旦发现某字符不在哈希表中,或者虽然是,但是在后面的对应位置上的字符不是它的“镜像对称”字符,就返回false。如果检查完所有的字符都没有问题,则返回true。
代码:
class Solution {
public:
bool isStrobogrammatic(string num) {
unordered_map<char, char> hash;
hash['0'] = '0';
hash['1'] = '1';
hash['8'] = '8';
hash['6'] = '9';
hash['9'] = '6';
int length = num.length();
for(int i = 0; i < (length + 1) / 2; ++i) {
if(hash.count(num[i]) == 0 || hash[num[i]] != num[length - 1 - i]) {
return false;
}
}
return true;
}
};
相关文章推荐
- leetcode 375. Guess Number Higher or Lower II 解题报告
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- LeetCode(306) Addtive Number解题报告
- [leetcode] 375. Guess Number Higher or Lower II 解题报告
- [leetcode] 171. Excel Sheet Column Number 解题报告
- [Leetcode] 374. Guess Number Higher or Lower 解题报告
- LeetCode 136. Single Number 解题报告
- 【LeetCode】Number of Boomerangs 解题报告
- LeetCode解题报告 --- Single Number II
- 【LeetCode】Excel Sheet Column Number 解题报告
- [leetcode]136. Single Number@Java解题报告
- 【LeetCode】Number of Segments in a String 解题报告
- 【LeetCode】Number Complement 解题报告
- [leetcode] 179. Largest Number 解题报告
- [Leetcode] 452. Minimum Number of Arrows to Burst Balloons 解题报告
- LeetCode 260. Single Number III 解题报告
- [Leetcode] 171. Excel Sheet Column Number 解题报告
- 【LeetCode】260. Single Number III 解题报告(Python)
- [leetcode] 263. Ugly Number 解题报告
- LeetCode-Excel Sheet Column Number-解题报告