1. 程式人生 > >[LeetCode] 246. Strobogrammatic Number 對稱數

[LeetCode] 246. Strobogrammatic Number 對稱數

map put 雙指針 har href .cn min repr amp

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.

翻轉180度後對稱的數有:8->8, 0->0, 1->1, 6->9, 9->6,從兩邊向中間檢查對應位置的兩個數是否滿足對稱數就行了。比如619,先判斷6和9是有映射的,然後1和自己又是映射,所以是對稱數。有點像判斷回文Palindrome,回文判斷是否相等,這裏判斷是否滿足那幾個數字的條件。判斷是可以直接寫條件判斷,也可以用HashMap存放數字的映射,然後用雙指針從兩邊向中間查看。

Java:

public class Solution {
    public boolean isStrobogrammatic(String num) {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put(‘1‘,‘1‘);
        map.put(‘0‘,‘0‘);
        map.put(‘6‘,‘9‘);
        map.put(‘9‘,‘6‘);
        map.put(‘8‘,‘8‘);
        int left = 0, right = num.length() - 1;
        while(left <= right){
            if(!map.containsKey(num.charAt(right)) || num.charAt(left) != map.get(num.charAt(right))){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

Python:

class Solution:
    lookup = {‘0‘:‘0‘, ‘1‘:‘1‘, ‘6‘:‘9‘, ‘8‘:‘8‘, ‘9‘:‘6‘}

    def isStrobogrammatic(self, num):
        n = len(num)
        for i in xrange((n+1) / 2):
            if num[n-1-i] not in self.lookup or                num[i] != self.lookup[num[n-1-i]]:
                return False
        return True

C++:

class Solution {
public:
    bool isStrobogrammatic(string num) {
        unordered_map<char, char> m {{‘0‘, ‘0‘}, {‘1‘, ‘1‘}, {‘8‘, ‘8‘}, {‘6‘, ‘9‘}, {‘9‘, ‘6‘}};
        for (int i = 0; i <= num.size() / 2; ++i) {
            if (m[num[i]] != num[num.size() - i - 1]) return false;
        }
        return true;
    }
};

 

類似題目: 

[LeetCode] 247. Strobogrammatic Number II 對稱數II

[LeetCode] 248. Strobogrammatic Number III 對稱數III

  

[LeetCode] 246. Strobogrammatic Number 對稱數