String pattern matching - backtracking --Java

Set of string length m
. 1, the first sub-character string with the character sequence is compared main string
2, if the same, then the following sub-strings of characters with the main character string following the current comparator m-1 characters compared in turn, until a different comparison result, or all the characters of the substring comparator finished
2-a, if all the characters in the substring in the comparison, then that match succeeds, the substring in the main string position is: the current main string pointer -. 1 m +
2-B, if the character does not match occurs during the comparison, the main string pointer back to the next position of the main string with the first character of the substring character comparison, but also a pointer substring back to the first string (1)
3, otherwise, the downward movement of a pointer main string, the substring string pointer back to the first

package string;

import java.util.Scanner;

public class Index {
    /*
    * 字符串模式匹配,回溯法
    * */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String sup = sc.nextLine();   //主串
        String sub = sc.nextLine();   //子串
        /*
        * 设字串长度为m
        * 1、用子串的第一个字符依次与主串的字符作比较
        * 2、如果相同,则用子串的下面的字符与主串中当前比较字符接下来的m-1个字符依次比较,直到比较结果不同或者子串后的所有字符比较完毕
        *   2-a、如果子串中的所有字符比较完毕,那么说明匹配成功,子串在主串中的位置就是:当前主串的指针 - m + 1
        *   2-b、如果比较过程中出现字符不匹配,则使主串的指针回溯到主串中与子串第一个字符比较的字符的下一个位置,同时子串指针也回溯到串首(1)
        * 3、否则,主串指针向下移动一位,子串指针回到串首
        * */
        int i = 0; //主串指针
        int j = 0; //子串指针
        while( i < sup.length() && j < sub.length()) {
            if (sup.charAt(i) == sub.charAt(j)) {
                i ++;
                j ++;
            } else {
                i = ((i - j + 1) + 1) -1;
                j = 0;
            }
        }
        if (j >= sub.length()) {
            System.out.println(sub + "在" + sup + "的第" + (i - j + 1) + "个字符处");
        } else {
            System.out.println(sup + "中没有" + sub);
        }
    }
}

Published 57 original articles · won praise 55 · views 1948

Guess you like

Origin blog.csdn.net/qq_40561126/article/details/104287731