Strobogrammatic Number

https://leetcode.com/problems/strobogrammatic-number/description/

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.

Thoughts

把一串数字翻180°还是原来的数字. 那么和回文一样必须两边对称, 和回文不同的是这次6和9是对称的, 然后0, 8, 1分别和对应的相同数字对称.

Code

class Solution {
    public boolean isStrobogrammatic(String num) {

        for (int l = 0, r = num.length() - 1; l <= r; l++, r--) {
            char c1 = num.charAt(l), c2 = num.charAt(r);
            if (c1 == c2 && "180".contains(c1 + "") || c1 == '6' && c2 == '9' || c1 == '9' && c2 == '6') {
                continue;
            }
            return false;
        }

        return true;
    }
}

Analysis

时间复杂度O(N)

Last updated