Leetcode 0246: 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.

Example 1:

Input: num = “69”
Output: true

Example 2:

Input: num = “88”
Output: true

Example 3:

Input: num = “962”
Output: false

Example 4:

Input: num = “1”
Output: true

Time complexity: O(n)
Space complexity : O(1)

class Solution {
    
    
    public boolean isStrobogrammatic(String num) {
    
    
        Map<Character, Character> map = new HashMap<> (
            Map.of('0', '0', '1', '1', '6', '9', '8', '8', '9', '6'));
        for(int l = 0, r = num.length()-1; l <= r; l++,r--){
    
    
            char lc = num.charAt(l);
            char rc = num.charAt(r);
            if(!map.containsKey(lc) || map.get(lc) != rc){
    
    
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113917118