一道笔试题 原

芝麻糖葫芦

``````/**
* 主要的工具类
* Created by Morven on 2017/5/18.
*/
public class RegularMacher {
private RegularMacher() {}

private static class RegularMacherHolder {
private static RegularMacher instance = new RegularMacher();
}

public static RegularMacher getInstance() {
return RegularMacherHolder.instance;
}

public int matchIndex(String source, String regular) {
char[] chars = regular.toCharArray();
for (int i = 0; i < source.length(); i++) {
int index = indexOf(source, i, chars, 0);
if (index > -1) return index;
}
return -1;
}

private int indexOf(String source, int beginIndex, char[] chars, int charIndex) {
char c = chars[charIndex];
if (c == '^') {
if (beginIndex > 0) {
return -1;
}
int index = indexOf(source, beginIndex, chars, charIndex + 1);
if (index > -1) {
return beginIndex;
}
return -1;
} else if (c == '\$') {
if (beginIndex < source.length()) {
return -1;
}
return beginIndex;
} else if (c == '.') {
} else if (c == '*') {
if (charIndex + 1 == chars.length) {
return beginIndex;
}
if (charIndex + 2 == chars.length && chars[charIndex + 1] == '\$') {
return beginIndex;
}
for (int i = beginIndex; i < source.length(); i++) {
int index = indexOf(source, i, chars, charIndex + 1);
if (index > -1) return index;
}
return -1;
} else {
if (c != source.charAt(beginIndex)) {
return -1;
}
}
if (charIndex + 1 == chars.length) return beginIndex;
if (beginIndex + 1 == source.length()) {
if (charIndex + 2 < chars.length) return -1;
}
int index = indexOf(source, beginIndex + 1, chars, charIndex + 1);
if (index > -1) {
return beginIndex;
}
return -1;
}
}

``````
``````/**
* 测试
* Created by Morven on 2017/5/18.
*/
public class RegularMacherTest {
public static void main(String[] args) {
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", ".est"));//0
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", ".ssdfa"));//-1
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", "^.aa"));//-1
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", "*"));//0
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", "*\$"));//0
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", "j*i"));//5
System.out.println(RegularMacher.getInstance().matchIndex("Test java in Action.", "j*ava"));//5
}
}
``````

芝麻糖葫芦

暂无文章

OSChina 周二乱弹 —— 以后我偷小鱼干养你

Osc乱弹歌单（2019）请戳（这里） 【今日歌曲】 @庞巴哥 ：只有这节奏瞬间变得轻松。。。。。。。。。分享Talking Eyes的单曲《In the sun (Extended Version)》: 《In the sun (Extended Ve...

36分钟前
1
0

stars永恒

7
0

o0无忧亦无怖

10
0
Mac Vim配置

1.升级 vim　　 我自己 MacBook Pro 的系统还是 10.11 ，其自带的 vim 版本为 7.3 ，我们将其升至最新版： 使用 homebrew ： brew install vim --with-lua --with-override-system-vim 这将下...

Pasenger

9
0
vmware安装Ubuntu上不了网？上网了安装不了net-tools，无法执行ifconfig？

1.重新设置网络适配器还是不行，如下指定nat 2.还需要指定共享网络，我是在无线环境下 3.无法执行ifconfig https://packages.ubuntu.com/bionic/net-tools到这个网站下载net-tools的deb文件...

noob_chr

7
0