246. Strobogrammatic Number - Easy

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:  "69"
Output: true

Example 2:

Input:  "88"
Output: true

Example 3:

Input:  "962"
Output: false

 

把符合条件的数字(0,1,6,8,9)放进HashMap,双指针分别从0, length-1位置向中间扫描字符串

time: O(n), space: O(1)

class Solution {
    public boolean isStrobogrammatic(String num) {
        Map<Character, Character> map = new HashMap<>();
        map.put('0', '0');
        map.put('1', '1');
        map.put('6', '9');
        map.put('8', '8');
        map.put('9', '6');
        
        int i = 0, j = num.length() - 1;
        while(i <= j) {
            char s = num.charAt(i), t = num.charAt(j);
            if(s != t && !map.containsKey(s) || !map.containsKey(t) || map.get(s) != t)
                return false;
            i++;
            j--;
        }
        return true;
    }
}

 

posted @ 2018-12-24 09:34  fatttcat  阅读(98)  评论(0编辑  收藏  举报