Leetcode 246: Strobogrammatic Number

问题描述:
Given a string num which represents an integer, return true if num is a strobogrammatic number.
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

解释说明:旋转180度后保持一致的几组数是:0和0,1和1,6和9,8和8, 9和6。两个指针从两端逼近,若遇到的不是以上这些组合,当机立断返回false。如果循环能正常结束(循环条件:左指针<=右指针),就返回true

代码如下:

class Solution {
    public boolean isStrobogrammatic(String num) {
        int left=0;
        int right=num.length()-1;
        while(left<=right){
            if(!(rotationValid(num.charAt(left), num.charAt(right))))   return false;
            left++;
            right--;
        }
        return true;
    }
    
    private boolean rotationValid(char a, char b){
        if((a=='0')&&(b=='0')) return true;
        else if((a=='1')&&(b=='1')) return true;
        else if((a=='6')&&(b=='9')) return true;
        else if((a=='8')&&(b=='8')) return true;
        else if((a=='9')&&(b=='6')) return true;
        else return false;
    }
}

时间复杂度:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值