1 package com.kk.string; 2 3 public class Main { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 char[] s = "要深入理解和精準把握黨的十九大精神,結合實際紮紮實實貫徹黨的十九大決策部署,緊扣中國特點社會主義新時代的新要求,推進黨和國家各項事業不斷邁上新臺階".toCharArray(); 10 char[] t = "新臺階".toCharArray(); 11 System.out.println(Main.index1(s, t, 0)); 12 System.out.println(Main.indexKMP(s, t, 0)); 13 14 } 15 16 /** 17 * 字符串的普通匹配算法 18 * 19 * @param s 20 * @param t 21 * @param pos 22 * @return 23 */ 24 public static int index1(char[] s, char[] t, int pos) { 25 int i = pos; 26 int j = 0; 27 while (i < s.length && j < t.length) { 28 if (s[i] == t[j]) { 29 i++; 30 j++; 31 } else { 32 i = i - j + 1; 33 j = 0; 34 } 35 } 36 if (j == t.length) 37 return i - j; 38 else 39 return -1; 40 } 41 42 /** 43 * 首尾匹配算法 44 * 45 * @param s 46 * @param t 47 * @param pos 48 * @return 49 */ 50 public static int index2(char[] s, char[] t, int pos) { 51 // int i = pos; 52 // int j = 0; 53 return -1; 54 } 55 56 /** 57 * KMP算法 58 * 59 * @param s 60 * @param t 61 * @param pos 62 * @return 63 */ 64 public static int indexKMP(char[] s, char[] t, int pos) { 65 int[] next = Main.getNextval(t); 66 int i = pos; 67 int j = 0; 68 while (i < s.length && j < t.length) { 69 if (j == -1 || s[i] == t[j]) { 70 j++; 71 i++; 72 } else { 73 j = next[j]; 74 } 75 } 76 if (j == t.length) 77 return i - j; 78 else 79 return -1; 80 } 81 82 /** 83 * getNext 84 * 85 * @param t 86 * @param next 87 */ 88 public static int[] getNext(char[] t) { 89 if (null == t || t.length == 0) 90 return null; 91 // 92 int[] next = new int[t.length]; 93 int j = 0; 94 int i = 0; 95 next[0] = -1; 96 while (i < t.length) { 97 if (j == 0 || t[i] == t[j]) { 98 next[i] = j - 1; 99 i++; 100 j++; 101 } else { 102 j = next[j]; 103 } 104 } 105 return next; 106 } 107 108 /** 109 * getNextval 110 * 111 * @param t 112 * @param next 113 */ 114 public static int[] getNextval(char[] t) { 115 if (null == t || t.length == 0) 116 return null; 117 // 118 int[] nextval = new int[t.length]; 119 int j = 0; 120 int i = 0; 121 nextval[0] = -1; 122 while (i < t.length) { 123 if (j == 0 || t[i] == t[j]) { 124 if (t[i] != t[j]) { 125 nextval[i] = j - 1; 126 } else { 127 nextval[i] = nextval[j]; 128 } 129 i++; 130 j++; 131 } else { 132 j = nextval[j]; 133 } 134 } 135 return nextval; 136 } 137 138 }