这里写代码片
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));
}
}
}
}