Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion solution/3400-3499/3407.Substring Matching Pattern/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,13 @@ tags:

<!-- solution:start -->

### 方法一
### 方法一:字符串匹配

根据题目描述,`*` 可以被替换为零个或多个字符组成的任意字符序列,因此我们可以将模式字符串 $p$ 按照 `*` 分割成若干个子串,如果这些子串依次出现在字符串 $s$ 中且顺序不变,则说明 $p$ 可以变成 $s$ 的子字符串。

因此,我们首先初始化一个指针 $i$ 指向字符串 $s$ 的起始位置,然后遍历模式字符串 $p$ 按照 `*` 分割得到的每个子串 $t$,在字符串 $s$ 中从位置 $i$ 开始查找子串 $t$,如果找到了,则将指针 $i$ 移动到子串 $t$ 的末尾位置继续查找下一个子串;如果找不到,则说明模式字符串 $p$ 不能变成字符串 $s$ 的子字符串,返回 $\text{false}$。如果所有子串都找到了,则返回 $\text{true}$。

时间复杂度 $O(n \times m)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别是字符串 $s$ 和模式字符串 $p$ 的长度。

<!-- tabs:start -->

Expand Down
26 changes: 25 additions & 1 deletion solution/3400-3499/3407.Substring Matching Pattern/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,13 @@ tags:

<!-- solution:start -->

### Solution 1
### Solution 1: String Matching

According to the problem description, `*` can be replaced by any sequence of zero or more characters, so we can split the pattern string $p$ by `*` into several substrings. If these substrings appear in order in the string $s$, then $p$ can become a substring of $s$.

Therefore, we first initialize a pointer $i$ to the start of string $s$, then iterate over each substring $t$ obtained by splitting the pattern string $p$ by `*`. For each $t$, we search for it in $s$ starting from position $i$. If it is found, we move the pointer $i$ to the end of $t$ and continue searching for the next substring. If it is not found, it means the pattern string $p$ cannot become a substring of $s$, and we return $\text{false}$. If all substrings are found, we return $\text{true}$.

The time complexity is $O(n \times m)$, and the space complexity is $O(m)$, where $n$ and $m$ are the lengths of strings $s$ and $p$, respectively.

<!-- tabs:start -->

Expand Down Expand Up @@ -174,6 +180,24 @@ function hasMatch(s: string, p: string): boolean {
}
```

#### Rust

```rust
impl Solution {
pub fn has_match(s: String, p: String) -> bool {
let mut i = 0usize;
for t in p.split('*') {
if let Some(j) = s[i..].find(t) {
i += j + t.len();
} else {
return false;
}
}
true
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
13 changes: 13 additions & 0 deletions solution/3400-3499/3407.Substring Matching Pattern/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
impl Solution {
pub fn has_match(s: String, p: String) -> bool {
let mut i = 0usize;
for t in p.split('*') {
if let Some(j) = s[i..].find(t) {
i += j + t.len();
} else {
return false;
}
}
true
}
}