• [LeetCode#246] Missing Ranges Strobogrammatic Number


    Problem:

    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.

    Analysis:

    This kind of problem is very very easy!!! Keep clam and carry on!
    Basic idea:
    1. identify which digits are valid for construct a Strobogrammatic Number.
    Instant idea: 0, 1, 8.
    Hint from the question: 6, 9
    private boolean isStroboDigit(Character c) {
        if (c == '0' || c == '1' || c == '6' || c == '8' || c == '9')
            return true;
        return false;
    }
    
    2. To look a num upside own is equal to reverse it. (with '6' change into '9', '9' change into '6')
    char c = num.charAt(i);
    if (isStroboDigit(c)) {
        if (c == '6')
            buffer.append('9');
        else if(c == '9')
            buffer.append('6');
        else 
            buffer.append(c);
    } else {
            return false;
    }
    
    My common mistakes in implementation:
    1. write : (forget to change i++ into i--, when realizing we should scan from the last charcter!)
    for (int i = len - 1; i >= 0; i--)
    into
    for (int i = len - 1; i >= 0; i++)
    
    
    2. return buffer.toString.equals(num);
    Forget () after toString method.

    Solution:

    public class Solution {
        public boolean isStrobogrammatic(String num) {
            if (num == null)
                throw new IllegalArgumentException("num is null");
            int len = num.length();
            if (len == 0)
                return true;
            StringBuffer buffer = new StringBuffer();
            for (int i = len - 1; i >= 0; i--) {
                char c = num.charAt(i);
                if (isStroboDigit(c)) {
                    if (c == '6')
                        buffer.append('9');
                    else if(c == '9')
                        buffer.append('6');
                    else 
                        buffer.append(c);
                } else {
                    return false;
                }
            }
            return buffer.toString().equals(num);
        }
        
        
        private boolean isStroboDigit(Character c) {
            if (c == '0' || c == '1' || c == '6' || c == '8' || c == '9')
                return true;
            return false;
        }
    }
  • 相关阅读:
    BEGIN
    bdflush
    BASH BUILTIN COMMANDS 内建命令
    程序 算法与数据结构
    ThinkPHP 3.2.2 在 volist 多重循环嵌套中使用 if 判断标签
    Java实现 蓝桥杯 算法提高 矩形靶
    Java实现 蓝桥杯 算法提高 矩形靶
    Java实现 蓝桥杯 算法提高 矩形靶
    Java实现 蓝桥杯 算法提高 歌唱比赛
    Java实现 蓝桥杯 算法提高 歌唱比赛
  • 原文地址:https://www.cnblogs.com/airwindow/p/4796836.html
Copyright © 2020-2023  润新知