创新工场笔试题

这里写代码片1写一个算法判断某个字符串是不是一个合法的IP地址。

正则表达式问题

String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

这是标准的匹配ipv4地址的写法,可以参考《精通正则表达式》第三版
^匹配开头
1\d{2}匹配1开头的三位数,例如192
2[0-4]\d匹配200至249之间的数字
25[0-5]匹配250至255之间的数字
[1-9]\d匹配两位数
[1-9]匹配一位数
.匹配ip地址中的句点(英文输入法)
$匹配结尾
ip地址4个部分的组成规则是一样的,所以重复了四段

 public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                      "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                      "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                      "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }

2给定一字符串只包含数字,请写一个算法,找出该字符串中的最长不重复子串(不重复是指子串中每一元素不同于子串中其他元素)

public static void longestNodupSubstring(String str) {  
        int len = str.length();  
        if (len > 0) {

            //charIndex里面存放字符在字符串中的位置
            Map<Character, Integer> charIndex = new HashMap<Character, Integer>();  
            charIndex.put(str.charAt(0), 0);  

            //lenAt[i]存放以字符string.charAt(i)结尾的最长子字符串的长度
            int[] lenAt = new int[str.length()]; 

            lenAt[0] = 1;  
            int max = 0;  

            for (int i = 1; i < len; i++) {  
                char c = str.charAt(i);  
                if (charIndex.containsKey(c)) {  
                    /*lenAt[i] = Math.min(lenAt[i - 1] + 1, i  
                            - charIndex.get(c));*/
                    lenAt[i] =  i  - charIndex.get(c);
                } else {  
                    lenAt[i] = lenAt[i - 1] + 1;  
                }  
                max = Math.max(max, lenAt[i]);  
                charIndex.put(c, i);  
            } 

            for (int i = 0; i < len; i++) {  
                if (max == lenAt[i]) {  
                    System.out.println(str.substring(i - max + 1, i + 1));  
                }  
            }  
        }  
    }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值