原题链接在这里: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.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
题解:
把几种对应关系加到HashMap中,两个指针向中间夹逼.
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public boolean isStrobogrammatic(String num) { 3 HashMap<Character, Character> hm = new HashMap<Character, Character>(); 4 hm.put(‘6‘,‘9‘); 5 hm.put(‘9‘,‘6‘); 6 hm.put(‘1‘,‘1‘); 7 hm.put(‘0‘,‘0‘); 8 hm.put(‘8‘,‘8‘); 9 10 int l = 0; 11 int r = num.length() - 1; 12 while(l <= r){ 13 if(!hm.containsKey(num.charAt(l))){ 14 return false; 15 }else if(hm.get(num.charAt(l)) != num.charAt(r)){ 16 return false; 17 }else{ 18 l++; 19 r--; 20 } 21 } 22 return true; 23 } 24 }
时间: 2024-11-01 01:13:09