Thinking Process

what numbers looks same when looked at upside down?

  • 0, 1, 8

which pair of numbers looks same when looked upside down?

  • 6, 9

what else this number has

  • it's palindrome

Then, how to make sure this is a palindrome

  • two pointers

What if the length is odd? What if it's even?

  • the condition in while

How can I know whether this is a match?

  • quick look up => Hash Table

Mistakes

be careful with spelling

API Method

Hash table
  • Initialization

>>>Mine

public class Solution {
    private HashMap<Character, Character> map = new HashMap<Character, Character>() {
        {
            put('6', '9'); put('9', '6'); put('1', '1'); put('8', '8'); put('0', '0');
        }
    };
    public boolean isStrobogrammatic(String num) {
        if (num.length() == 0) return true;
        char[] nums = num.toCharArray();
        int left = 0;
        int right = num.length() - 1;

        while (left <= right) {
            if (!map.containsKey(nums[left]) || !map.containsKey(nums[right])) return false;
            else if (map.containsKey(nums[left]) && map.get(nums[left]) != nums[right]) return false;

            left++;
            right--;
        }

        return true;
    }
}

>>>>Advanced Version

public class Solution {
    public boolean isStrobogrammatic(String num) {
        for (int i = 0, j = num.length() - 1; i <= j; i++, j--) {
            if (!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) return false;
        }

        return true;
    }
}

results matching ""

    No results matching ""