LeetCode Strobogrammatic Number

时间:2022-03-21 08:45:02

原题链接在这里:https://leetcode.com/problems/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.

Example 1:

Input:  "69"
Output: true

Example 2:

Input:  "88"
Output: true

Example 3:

Input:  "962"
Output: false

题解:

把几种对应关系加到HashMap中,两个指针向中间夹逼.

Time Complexity: O(n). Space: O(1).

AC Java:

 class Solution {
public boolean isStrobogrammatic(String num) {
if(num == null || num.length() == 0){
return true;
} HashMap<Character, Character> hm = new HashMap<>();
String cans = "0011886996";
for(int i = 0; i<cans.length(); i+=2){
hm.put(cans.charAt(i), cans.charAt(i+1));
} int l = 0;
int r = num.length() - 1;
while(l <= r){
char left = num.charAt(l);
char right = num.charAt(r);
if(!hm.containsKey(left) || !hm.containsKey(right) || hm.get(left) != right || hm.get(right) != left){
return false;
} l++;
r--;
} return true;
}
}

跟上Strobogrammatic Number IIStrobogrammatic Number III.