246. 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.

class Solution {
    public boolean isStrobogrammatic(String num) {
        if (num == null || num.length() == 0) return true;

        Map<Character, Character> hash = new HashMap<>();
        hash.put('1', '1');
        hash.put('8', '8');
        hash.put('6', '9');
        hash.put('9', '6');
        hash.put('0', '0');

        char[] cArray = num.toCharArray();
        reverse(cArray);
        convert(cArray, hash);

        return String.valueOf(cArray).equals(num);
    }

    private void reverse(char[] cArray){
        int start = 0, end = cArray.length - 1;
        while (start < end){
            char temp = cArray[start];
            cArray[start] = cArray[end];
            cArray[end] = temp;

            start++;
            end--;
        }
    }

    private void convert(char[] cArray, Map<Character, Character> hash){
        for (int i = 0; i < cArray.length; i++){
            if (hash.containsKey(cArray[i])){
                cArray[i] = hash.get(cArray[i]);
            }
            else{
                cArray[i] = '*';
            }
        }

    }
}

results for ""

    No results matching ""