比较两个串(是否为包含另外一个),如果包含,输出主串的起始下标:
public class BruteForce {
public static void main(String[] args) {
String s1 = "asdasdasdffffffggggg"; //主串
String s2 = "asdf"; //子串
int index = strIndex(s1, s2);
System.out.println("index = " + index);
}
public static int strIndex(String str, String str1) {
int i = 0,j = 0,start = 0;
char[] s = str.toCharArray();
char[] t = str1.toCharArray();
if (t.length == 0)
return -1;
while (i < s.length && j < t.length) {
if (s[i] == t[j]) {
i++;j++;
}else {
start++;
i = start;
j=0;
}
}
if (j >= t.length)
return start;
else
return -1;
}
}
网友评论