字符串匹配算法之Sunday算法(二)
;
92 currentPos += 1;
93 sundayMatch();
94 }
95 return matchedPosList;
96 }
97
98 /**
99 * 检查从Text的指定偏移量开始的子串是否和Pattern匹配
100 */
101 public boolean matchFromSpecialPos(int pos) {
102 if ((text.length()-pos) < pattern.length()) {
103 return false;
104 }
105
106 for (int i = 0; i < pattern.length(); i++) {
107 if (text.charAt(pos + i) == pattern.charAt(i)) {
108 if (i == (pattern.length()-1)) {
109 return true;
110 }
111 continue;
112 } else {
113 break;
114 }
115 }
116
117 return false;
118 }
119
120 public static void main(String[] args) {
122
123 long begin = System.nanoTime();
124 System.out.println("NormalMatch:" + sundySearch.normalMatch());
125 System.out.println("NormalMatch:" + (System.nanoTime() - begin));
126
127 begin = System.nanoTime();
128 System.out.println("SundayMatch:" + sundySearch.sundayMatch());
129 System.out.println("SundayMatch:" + (System.nanoTime() - begin));
130
131 }
132 }
运行结果:
NormalMatch:[13, 17, 24]
NormalMatch:313423
SundayMatch:[13, 17, 24]
SundayMatch:36251
使用Sunday算法要比普通的匹配算法快了10倍左右,虽然是纳秒级别~因为我们匹配的内容就那么短,内容越长,效果就会越明显。
每个人都可以以自己的方式实现这个算法,如有雷同,纯属巧合。。。