@@ -1059,5 +1059,112 @@ func getNext(_ next: inout [Int], needle: [Character]) {
10591059
10601060```
10611061
1062+ > 前缀表右移
1063+
1064+ ``` swift
1065+ func strStr (_ haystack : String , _ needle : String ) -> Int {
1066+
1067+ let s = Array (haystack), p = Array (needle)
1068+ guard p.count != 0 else { return 0 }
1069+
1070+ var j = 0
1071+ var next = [Int ].init (repeating : 0 , count : p.count )
1072+ getNext (& next, p)
1073+
1074+ for i in 0 ..< s.count {
1075+
1076+ while j > 0 && s[i] != p[j] {
1077+ j = next[j]
1078+ }
1079+
1080+ if s[i] == p[j] {
1081+ j += 1
1082+ }
1083+
1084+ if j == p.count {
1085+ return i - p.count + 1
1086+ }
1087+ }
1088+
1089+ return -1
1090+ }
1091+
1092+ // 前缀表后移一位,首位用 -1 填充
1093+ func getNext (_ next : inout [Int ], _ needle : [Character ]) {
1094+
1095+ guard needle.count > 1 else { return }
1096+
1097+ var j = 0
1098+ next[0 ] = j
1099+
1100+ for i in 1 ..< needle.count - 1 {
1101+
1102+ while j > 0 && needle[i] != needle[j] {
1103+ j = next[j- 1 ]
1104+ }
1105+
1106+ if needle[i] == needle[j] {
1107+ j += 1
1108+ }
1109+
1110+ next[i] = j
1111+ }
1112+ next.removeLast ()
1113+ next.insert (-1 , at : 0 )
1114+ }
1115+ ```
1116+
1117+ > 前缀表统一不减一
1118+ ``` swift
1119+
1120+ func strStr (_ haystack : String , _ needle : String ) -> Int {
1121+
1122+ let s = Array (haystack), p = Array (needle)
1123+ guard p.count != 0 else { return 0 }
1124+
1125+ var j = 0
1126+ var next = [Int ](repeating : 0 , count : needle.count )
1127+ // KMP
1128+ getNext (& next, needle : p)
1129+
1130+ for i in 0 ..< s.count {
1131+ while j > 0 && s[i] != p[j] {
1132+ j = next[j- 1 ]
1133+ }
1134+
1135+ if s[i] == p[j] {
1136+ j += 1
1137+ }
1138+
1139+ if j == p.count {
1140+ return i - p.count + 1
1141+ }
1142+ }
1143+ return -1
1144+ }
1145+
1146+ // 前缀表
1147+ func getNext (_ next : inout [Int ], needle : [Character ]) {
1148+
1149+ var j = 0
1150+ next[0 ] = j
1151+
1152+ for i in 1 ..< needle.count {
1153+
1154+ while j> 0 && needle[i] != needle[j] {
1155+ j = next[j- 1 ]
1156+ }
1157+
1158+ if needle[i] == needle[j] {
1159+ j += 1
1160+ }
1161+
1162+ next[i] = j
1163+
1164+ }
1165+ }
1166+
1167+ ```
1168+
10621169-----------------------
10631170<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments