Skip to content

feat: add rust solution to lc problem: No.3330 #4525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 25, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,15 @@ tags:

<!-- solution:start -->

### 方法一
### 方法一:直接遍历

根据题目描述,如果所有相邻字符都不相同,那么只有 1 种可能的输入字符串;如果有 1 对相邻字符相同,例如 "abbc",那么可能的输入字符串有 2 种:"abc" 和 "abbc"。

依此类推,如果有 $k$ 对相邻字符相同,那么可能的输入字符串有 $k + 1$ 种。

因此,我们只需要遍历字符串,统计相邻字符相同的对数再加 1 即可。

时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。空间复杂度 $O(1)$。

<!-- tabs:start -->

Expand Down Expand Up @@ -144,6 +152,16 @@ function possibleStringCount(word: string): number {
}
```

#### Rust

```rust
impl Solution {
pub fn possible_string_count(word: String) -> i32 {
1 + word.as_bytes().windows(2).filter(|w| w[0] == w[1]).count() as i32
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,15 @@ tags:

<!-- solution:start -->

### Solution 1
### Solution 1: Direct Traversal

According to the problem description, if all adjacent characters are different, there is only 1 possible original input string. If there is 1 pair of adjacent identical characters, such as "abbc", then there are 2 possible original strings: "abc" and "abbc".

By analogy, if there are $k$ pairs of adjacent identical characters, then there are $k + 1$ possible original input strings.

Therefore, we just need to traverse the string, count the number of pairs of adjacent identical characters, and add 1.

The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$.

<!-- tabs:start -->

Expand Down Expand Up @@ -142,6 +150,16 @@ function possibleStringCount(word: string): number {
}
```

#### Rust

```rust
impl Solution {
pub fn possible_string_count(word: String) -> i32 {
1 + word.as_bytes().windows(2).filter(|w| w[0] == w[1]).count() as i32
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
impl Solution {
pub fn possible_string_count(word: String) -> i32 {
1 + word.as_bytes().windows(2).filter(|w| w[0] == w[1]).count() as i32
}
}