zoukankan      html  css  js  c++  java
  • 暴力破解--通俗易通

    一.什么是暴力破解

      对于字符串的匹配问题,可以用暴力破解。

      假设现在 str1 匹配到 i 位置,子串 str2 匹配到 j 位置,则有:

        1.如果当前字符匹配成功(即 str1[i] == str2[j]),则 i++,j++,继续匹配下一个字符

        2.如果不匹配(即 str1[i]! = str2[j]),令 i = i - (j - 1),j = 0。相当于每次匹配失败时,i 回溯,j 被置为 0,也就是重新开始下次匹配,str1下次匹配的字符后移1位,子串重新置为0从第1个字符位置重新再进行匹配。

        3.这样匹配的问题是,可以找到子串出现位置的脚标,如果在没有匹配到时,会有大量的回溯和重置,之前匹配过的会全部失效,会重新进行匹配,浪费时间。

    二.代码实现

    public class ViolenceMatch {
    
        public static void main(String[] args) {
            String s1 = "abcdefadf";
            String s2 = "adf";
            int index = violenceCrack(s1, s2);
            System.out.println("index ==>" + index);
    
        }
    
        public static int violenceCrack(String s1, String s2) {
    
            char c1[] = s1.toCharArray(); // abcdefadf
            char c2[] = s2.toCharArray(); // abf
    
            int srcLeng = s1.length();
            int desLeng = s2.length();
    
            int i = 0;
            int j = 0;
    
            while (i < srcLeng && j < desLeng) {
                if (c1[i] == c2[j]) {
                    i++; // a i=1 b i=2
                    j++; // a j=1 b j=2
                } else {
                    j = 0; // 将s2字符串置为0,重新与s1字串进行比较 j = 0
                    i = i - (j - 1); // s1字符串需要后移1位,继续与s2字符串的第0位进行比较 i = 1 在下一轮的比较中也就是s1串的的c与s2字符串的a重新进行比较
                }
            }
    
            if (j == desLeng) { // 当比较结束时,也就是j的长度与s2字符串的长度相等了,此时也就找到了s2字符串在s1字符串中的索引
                return i - j;
            } else {
                return -1;
            }
        }
    }
  • 相关阅读:
    6-1
    4-9
    4-5
    4-4
    4-3
    3-10
    作业三2
    作业三1
    课堂练习二
    实验三
  • 原文地址:https://www.cnblogs.com/MrRightZhao/p/12116892.html
Copyright © 2011-2022 走看看