2015年9月10日星期四

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.
For example, the numbers "69", "88", and "818" are all strobogrammatic.

public class Solution {
    public boolean isStrobogrammatic(String num) {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put('6', '9');
        map.put('9', '6');
        map.put('0', '0');
        map.put('1', '1');
        map.put('8', '8');
       
        int start = 0;
        int end = num.length() - 1;
        if (num == null || num.length() == 0) {
            return false;
        }
        while (start <= end) {
            char c1 = num.charAt(start);
            char c2 = num.charAt(end);
            if (map.containsKey(c1) && map.get(c1) == c2) {
                start++;
                end--;
            } else {
                return false;
            }
        }
        return true;
    }
}

没有评论:

发表评论