java模式比對之蠻力匹配

來源:互聯網
上載者:User

java模式比對之蠻力匹配

   這篇文章主要介紹了java模式比對之蠻力匹配的相關資料和代碼,需要的朋友可以參考下

  java模式比對之蠻力匹配

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

/**

* 模式比對之蠻力匹配

*/

package javay.util;

 

/**

* Pattern Match Brute-Force

* @author DBJ

*/

public class PMBF {

 

/**

* Pattern Match Brute-Force

* @param target 目標串

* @param pattern 模式串

* @return 模式串在目標串中第一次出現的位置

*/

public static int patternMatch(String target, String pattern) {

int targetLength = target.length();

int patternLength = pattern.length();

int idxTgt = 0; // 目標串中字元的位置

int idxPtn = 0; // 模式串中字元的位置

 

int index = 0; // 儲存與模式串匹配ing的起始字元的位置

while(idxTgt < targetLength && idxPtn < patternLength) {

//找到一個匹配的字元

if(target.charAt(idxTgt) == pattern.charAt(idxPtn)) {

// 如果相等,則繼續對字元進行後續的比較

idxTgt ++;

idxPtn ++;

} else {

// 否則目標串從第二個字元開始與模式串的第一個字元重新比較

index ++;

idxPtn = 0;

idxTgt = index;

}

}

// 匹配到一個,輸出結果

if(idxPtn == patternLength) {

//說明匹配成功

return index;

} else {

return -1;

}

}

}

  使用樣本:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

static int indexOf(char[] source,char[] target) {

char first = target[0];

int max = (source.length - target.length);

for (int i = 0; i <= max; i++) {

/* Look for first character. */

if (source[i] != first) {

while (++i <= max && source[i] != first);

}

/* Found first character, now look at the rest of v2 */

if (i <= max) {

int j = i + 1;

int end = j + target.length - 1;

for (int k = 1; j < end && source[j] == target[k]; j++, k++);

if (j == end) {

/* Found whole string. */

return i ;

}

}

}

return -1;

}

  以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.