LeetCode算法246: 中心对称数

编程入门 行业动态 更新时间:2024-10-26 11:13:52

LeetCode算法246: 中心<a href=https://www.elefans.com/category/jswz/34/1763015.html style=对称数"/>

LeetCode算法246: 中心对称数

LeetCode算法246: 中心对称数

链接: /

题目描述

中心对称数是指一个数字在旋转了 180 度之后看起来依旧相同的数字(或者上下颠倒地看)。
请写一个函数来判断该数字是否是中心对称数,其输入将会以一个字符串的形式来表达数字。

C++代码解答

解法一

将字符串翻转,判断翻转之后的字符串是否与原字符串相等。

class Solution {
public:bool isStrobogrammatic(std::string num) {if (num.empty()) {return false;}std::unordered_map<char, char> table{{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};std::string rotate;for (auto it = num.rbegin(); it != num.rend(); ++it) {if (table.count(*it) == 0) {return false;}rotate.push_back(table[*it]);}return rotate == num;}
};

解法二

class Solution {
public:bool isStrobogrammatic(std::string num){if (num.empty()) {return false;}std::size_t len = num.size();std::unordered_map<char, char> table{{'0', '0'}, {'1', '1'}, {'8', '8'}, {'6', '9'}, {'9', '6'}};for (std::size_t i = 0; i < len / 2; ++i) {if (table(num[i]) != num[len - 1 - i]) {return false;}}return true;}
}

更多推荐

LeetCode算法246: 中心对称数

本文发布于:2024-02-12 03:27:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1685619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对称   算法   中心   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!