diff --git a/solution/3300-3399/3330.Find the Original Typed String I/README.md b/solution/3300-3399/3330.Find the Original Typed String I/README.md index 5c9ac9f00ee7e..bb17b3ef56cf3 100644 --- a/solution/3300-3399/3330.Find the Original Typed String I/README.md +++ b/solution/3300-3399/3330.Find the Original Typed String I/README.md @@ -75,7 +75,15 @@ tags: -### 方法一 +### 方法一:直接遍历 + +根据题目描述,如果所有相邻字符都不相同,那么只有 1 种可能的输入字符串;如果有 1 对相邻字符相同,例如 "abbc",那么可能的输入字符串有 2 种:"abc" 和 "abbc"。 + +依此类推,如果有 $k$ 对相邻字符相同,那么可能的输入字符串有 $k + 1$ 种。 + +因此,我们只需要遍历字符串,统计相邻字符相同的对数再加 1 即可。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。空间复杂度 $O(1)$。 @@ -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 + } +} +``` + diff --git a/solution/3300-3399/3330.Find the Original Typed String I/README_EN.md b/solution/3300-3399/3330.Find the Original Typed String I/README_EN.md index e6708d554969c..b9b50576bfb60 100644 --- a/solution/3300-3399/3330.Find the Original Typed String I/README_EN.md +++ b/solution/3300-3399/3330.Find the Original Typed String I/README_EN.md @@ -73,7 +73,15 @@ tags: -### 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)$. @@ -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 + } +} +``` + diff --git a/solution/3300-3399/3330.Find the Original Typed String I/Solution.rs b/solution/3300-3399/3330.Find the Original Typed String I/Solution.rs new file mode 100644 index 0000000000000..ae49c4100828a --- /dev/null +++ b/solution/3300-3399/3330.Find the Original Typed String I/Solution.rs @@ -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 + } +}