
package algorithm;
import java.util.Scanner;
/**
* @author: xyz
* @create: 2022/8/11
* @Description:
* @FileName: Exercise22_03
* @History:
* @自定义内容:模式匹配
*/
public class Exercise22_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string s1: ");
String s1 = input.nextLine();
System.out.print("Enter a string s2: ");
String s2 = input.nextLine();
int index = indexOf(s1, s2);s2.indexOf(s1);
System.out.println((index == -1 ? "Not " : "") + "matched at index " + index);
}
/** 模式匹配-s2是否是s1的子串 */
public static int indexOf(String s1, String s2) {
if (s2.length() > s1.length()) //s2长度大于s1长度,非子串
return -1;
int i =0, j = 0; //s1起始下标、s2起始下标
while (i < s1.length() && j < s2.length()) {
if (s1.charAt(i) == s2.charAt(j)) { //匹配字符
i++; j++;
} else { //不匹配字符
i = i - j + 1;
j = 0;
}
//匹配成功,退出循环
if (j == s2.length()) break;
}
//匹配成功,返回下标,否则返回-1
return j >= s2.length() ? i - s2.length() : -1;
}
}

6562

被折叠的 条评论
为什么被折叠?



