zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    Related to confusing number

    O(N) time and O(N) space

     1 public class Solution {
     2     public boolean isStrobogrammatic(String num) {
     3         if (num==null || num.length()==0) return false;
     4         StringBuffer buf = new StringBuffer();
     5         for (int i=0; i<num.length(); i++) {
     6             char c = num.charAt(i);
     7             if (c!='0' && c!='1' && c!='6' && c!= '8' && c!= '9') return false;
     8             else if (c=='0' || c=='1' || c=='8') buf.insert(0, c);
     9             else if (c == '6') buf.insert(0, '9');
    10             else if (c == '9') buf.insert(0, '6');
    11         }
    12         return buf.toString().equals(num);
    13     }
    14 }

     O(N) time and O(1) space, use two pointers

     1 public class Solution {
     2     public boolean isStrobogrammatic(String num) {
     3         HashMap<Character, Character> map = new HashMap<Character, Character>();
     4         map.put('1','1');
     5         map.put('0','0');
     6         map.put('6','9');
     7         map.put('9','6');
     8         map.put('8','8');
     9         int left = 0, right = num.length() - 1;
    10         while(left <= right){
    11             // 如果字母不存在映射或映射不对,则返回假
    12             if(!map.containsKey(num.charAt(right)) || num.charAt(left) != map.get(num.charAt(right))){
    13                 return false;
    14             }
    15             left++;
    16             right--;
    17         }
    18         return true;
    19     }
    20 }
  • 相关阅读:
    docker基本命令
    vscode 保存提示运行"XXX"的保存参与者: 快速修复
    Vue 2.6 插槽
    代码大全-PartOne-变量命名
    Axure 8.0.1.3388 注册码 授权码 破解
    乱七八糟记一下乱七八糟的碎片化知识
    JavaScript需记的一些细节
    Python3.6问题
    python3.6- shape mismatch: objects cannot be broadcast to a single shape
    Angular+ng-zorro遇坑记
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5062385.html
Copyright © 2011-2022 走看看