【Lintcode】644. Strobogrammatic Number

Title address:

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

Given an integer in the form of a string, judge to rotate it 180 ° 180\degree Whether the number obtained after is equal to yourself.

Write an additional number to determine whether the two numbers are centrally symmetric to each other. Then use the double pointer to judge all the way like the palindrome. If there is only one number left in the middle, you also need to determine whether the number itself is centrosymmetric. code show as below:

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;
        }
    }
}

time complexity THE ( n ) O (n) n n is the length of the number. space THE ( 1 ) O (1)

Published 388 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105355778