diff --git a/solution/3400-3499/3407.Substring Matching Pattern/README.md b/solution/3400-3499/3407.Substring Matching Pattern/README.md index 39ed56168bf5a..53158bf41521f 100644 --- a/solution/3400-3499/3407.Substring Matching Pattern/README.md +++ b/solution/3400-3499/3407.Substring Matching Pattern/README.md @@ -80,7 +80,13 @@ tags: -### 方法一 +### 方法一:字符串匹配 + +根据题目描述,`*` 可以被替换为零个或多个字符组成的任意字符序列,因此我们可以将模式字符串 $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$ 的长度。 diff --git a/solution/3400-3499/3407.Substring Matching Pattern/README_EN.md b/solution/3400-3499/3407.Substring Matching Pattern/README_EN.md index eeedc9ccf096c..48c6b6f6d8a86 100644 --- a/solution/3400-3499/3407.Substring Matching Pattern/README_EN.md +++ b/solution/3400-3499/3407.Substring Matching Pattern/README_EN.md @@ -78,7 +78,13 @@ tags: -### 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. @@ -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 + } +} +``` + diff --git a/solution/3400-3499/3407.Substring Matching Pattern/Solution.rs b/solution/3400-3499/3407.Substring Matching Pattern/Solution.rs new file mode 100644 index 0000000000000..4aa4cab8c8d68 --- /dev/null +++ b/solution/3400-3499/3407.Substring Matching Pattern/Solution.rs @@ -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 + } +}