首页 文章详情

​LeetCode刷题实战246:中心对称数

程序IT圈 | 407 2021-04-25 14:01 0 0 0
UniSMS (合一短信)
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 中心对称数,我们先来看题面:
https://leetcode-cn.com/problems/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.

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

示例


示例 1:
输入: "69"
输出: true

示例 2:
输入: "88"
输出: true

示例 3:
输入: "962"
输出: false


解题


翻转后对称的数就那么几个,我们可以根据这个建立一个映射关系:8->8, 0->0, 1->1, 6->9, 9->6,然后从两边向中间检查对应位置的两个字母是否有映射关系就行了。比如619,先判断6和9是有映射的,然后1和自己又是映射,所以是对称数。

public class Solution {
    public boolean isStrobogrammatic(String num) {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put('1','1');
        map.put('0','0');
        map.put('6','9');
        map.put('9','6');
        map.put('8','8');
        int left = 0, right = num.length() - 1;
        while(left <= right){
            // 如果字母不存在映射或映射不对,则返回假
            if(!map.containsKey(num.charAt(right)) || num.charAt(left) != map.get(num.charAt(right))){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-240题汇总,希望对你有点帮助!
LeetCode刷题实战241:为运算表达式设计优先级
LeetCode刷题实战242:有效的字母异位词
LeetCode刷题实战243:最短单词距离
LeetCode刷题实战244:最短单词距离 II
LeetCode刷题实战245:最短单词距离 III

good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter