题目:
给定一个字符串str和子串s,找出含有连续两次s作为子串的最短字符串,如str="as11as111as",s="as",输出:as11as,
特殊情况,str="asasa11asa",s="asa",输出:asasa
代码:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Short {
/**
* 为防止出现题目中所述包含情况匹配不到,采取匹配一次后将匹配字符串第一位截取掉重新匹配的方式
* 并记录每次的索引加一放入list
*/
public static void GetIndex(String s, String str) {
String str1 = str;
// 存储将字符串截取后匹配的索引
List<Integer> list = new ArrayList<Integer>();
while (true) {
String re = s;
Pattern p = Pattern.compile(re);
Matcher m = p.matcher(str1);
// 只匹配字符串一次,并在匹配位置后截取掉第一个字符(如:aba变成ba),这样下一次匹配就不会匹配到上一次的位置
// 将匹配位置存入list,这是只有第一个多加了一个1,所有位置的加和减一即为针对str的索引
if (m.find()) {
str1 = str1.substring(m.start() + 1, str1.length());
list.add(m.start() + 1);
//System.out.println(m.start() + "," + str1);
} else {
break;
}
}
int min = list.get(1);
// 取出间隔最小时,第二组匹配字符串位置
int index = 1;
for (int i = 1; i < list.size(); i++) {
int temp = list.get(i);
if (min > temp) {
min = temp;
index = i;
}
}
int submit = 0;
int startIndex = 0;
for (int j = 0; j <= index; j++) {
submit += list.get(j);
if (j == index) {
startIndex = submit - list.get(j) - 1;
}
}
int endIndex = submit + s.length() - 1;
String result = str.substring(startIndex, endIndex);
System.out.println(result);
}
public static void main(String[] args) {
try {
long st = System.nanoTime();
GetIndex("asa", "asasa11asa");
long end = System.nanoTime();
System.out.println(end - st);
} catch (Exception e) {
System.out.println("请检查字符串");
}
}
}
asasa
1402699
算的太复杂了,希望可以优化一下