246. 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.

一刷
two pointer

public class Solution {
    public boolean isStrobogrammatic(String num) {
        int lo = 0, hi = num.length()-1;
        while(lo<hi){
            char l = num.charAt(lo);
            char r = num.charAt(hi);
            if(l == '6'){
                if(r!='9') return false;
                lo++;
                hi--;
            }else if(l == '8'){
               if(r!='8') return false;
                lo++;
                hi--; 
            }else if(l == '9'){
                if(r!='6') return false;
                lo++;
                hi--;
            }else if(l == '1'){
                if(r!='1') return false;
                lo++;
                hi--;
            }else if(l == '0'){
                if(r!='0') return false;
                lo++;
                hi--;
            }
            else return false;
        }
        char l = num.charAt(lo);
        if(lo == hi) return l == '1' || l == '8' || l == '0';
        return true;
    }
}

二刷
短一点

public class Solution {
    public boolean isStrobogrammatic(String num) {
    String[] stro = {"11", "88", "69", "96", "00"};
    Set<String> dict = new HashSet<>(Arrays.asList(stro));
    for (int i=0, j=num.length()-1; i <= j; i++, j--){
        if(i==j){
            if(num.charAt(i)!='1' && num.charAt(i)!='8' && num.charAt(i)!='0') return false;
        }else{
            if (!dict.contains(num.charAt(i) + "" + num.charAt(j)))
            return false;
        }
    }
    return true;
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容