algorithm-base/animation-simulation/数据结构和算法/BF算法.md

191 lines
7.5 KiB
Java
Raw Normal View History

2021-03-21 04:53:14 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:58:25 +00:00
> leetcode AC
666 西
S T S T S T T S -1
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/字符串匹配.3q9wqbh8ws40.png)
T = baab, S = abcabaabcabac T S 4 0 4 T S -1
## BFBrute Force
![](https://img-blog.csdnimg.cn/20210319193924425.gif)
### leetcdoe 28. strStr()
####
haystack needle haystack needle (0) -1
1:
> : haystack = "hello", needle = "ll"
> : 2
2:
> : haystack = "aaaaa", needle = "bba"
> : -1
####
0
####
Java Code:
2021-03-20 07:58:25 +00:00
```java
class Solution {
public int strStr(String haystack, String needle) {
int haylen = haystack.length();
int needlen = needle.length();
//特殊情况
if (haylen < needlen) {
return -1;
}
if (needlen == 0) {
return 0;
}
//主串
for (int i = 0; i < haylen - needlen + 1; ++i) {
int j;
//模式串
for (j = 0; j < needlen; j++) {
//不符合的情况,直接跳出,主串指针后移一位
if (haystack.charAt(i+j) != needle.charAt(j)) {
break;
}
}
//匹配成功
if (j == needlen) {
return i;
}
}
return -1;
}
}
```
Python Code:
```python
from typing import List
class Solution:
def strStr(self, haystack: str, needle: str)->int:
haylen = len(haystack)
needlen = len(needle)
#
if haylen < needlen:
return -1
if needlen == 0:
return 0
#
for i in range(0, haylen - needlen + 1):
#
j = 0
while j < needlen:
if haystack[i + j] != needle[j]:
break
j += 1
#
if j == needlen:
return i
return -1
```
2021-03-20 07:58:25 +00:00
BF退
Java Code:
2021-03-20 07:58:25 +00:00
```java
class Solution {
public int strStr(String haystack, String needle) {
//i代表主串指针j模式串
int i,j;
//主串长度和模式串长度
int halen = haystack.length();
int nelen = needle.length();
//循环条件,这里只有 i 增长
for (i = 0 , j = 0; i < halen && j < nelen; ++i) {
//相同时,则移动 j 指针
if (haystack.charAt(i) == needle.charAt(j)) {
++j;
} else {
//不匹配时,将 j 重新指向模式串的头部,将 i 本次匹配的开始位置的下一字符
i -= j;
j = 0;
}
}
//查询成功时返回索引,查询失败时返回 -1
int renum = j == nelen ? i - nelen : -1;
return renum;
}
}
```
Python Code:
```python
from typing import List
class Solution:
def strStr(self, haystack: str, needle: str)->int:
# ij
i = 0
j = 0
#
halen = len(haystack)
nelen = len(needle)
# i
while i < halen and j < nelen:
# j
if haystack[i] == needle[j]:
j += 1
else:
# j i
i -= j
j = 0
i += 1
# -1
renum = i - nelen if j == nelen else -1
return renum
```