【Lintcode】644. Strobogrammatic Number

题目地址:

https://www.lintcode.com/problem/strobogrammatic-number/description

给定一个字符串形式的整数,判断将其旋转 180 ° 180\degree 后得到的数是否等于自己。

额外写一个数专门判断两个数是否互为中心对称即可。然后像判断回文串一样用双指针一路判断。如果中间只剩下一个数了,还需要判断一下这个数本身是否是中心对称的。代码如下:

public class Solution {
    /**
     * @param num: a string
     * @return: true if a number is strobogrammatic or false
     */
    public boolean isStrobogrammatic(String num) {
        // write your code here
        int l = 0, r = num.length() - 1;
        while (l < r) {
            if (!rotate(num.charAt(l) - '0', num.charAt(r) - '0')) {
                return false;
            }
            l++;
            r--;
        }
        // 如果只剩一个数,判断一下这个数本身是否中心对称;否则直接返回true
        if (l == r) {
            char c = num.charAt(l);
            return c == '0' || c == '1' || c == '8';
        } else {
            return true;
        }
    }
    
    private boolean rotate(int x, int y) {
        switch (x) {
            case 0:
                return y == 0;
            case 1:
                return y == 1;
            case 2:
                return y == 5;
            case 5:
                return y == 2;
            case 6:
                return y == 9;
            case 8:
                return y == 8;
            case 9:
                return y == 6;
            default:
                return false;
        }
    }
}

时间复杂度 O ( n ) O(n) n n 为数字的长度。空间 O ( 1 ) O(1)

发布了388 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105355778