2025-05-19:找到初始输入字符串Ⅰ。用go语言,Alice 在电脑上输入一个字符串时,可能会因为按键时间过长,导致某个字符被重复输入多次。尽管她尽力避免犯错,但最终的输入结果最多只有一次此类重复错误。
给定一个字符串 word,表示她输入后显示在屏幕上的内容。请你计算,有多少种不同的字符串,可能是她最初想输入的原始内容。换句话说,统计所有可能的原始字符串数量,使得经过最多一次重复按键导致的字符延长后,能得到 word 这个字符串。
1 <= word.length <= 100。
word 只包含小写英文字母。
输入:word = "abbcccc"。
输出:5。
解释:
可能的字符串包括:"abbcccc" ,"abbccc" ,"abbcc" ,"abbc" 和 "abcccc"。
题目来自力扣3300。
word
中所有连续的相同字符的序列。例如,"abbcccc" 可以分解为:n
的连续字符序列:n
。n-1
(前提是 n > 1
)。word
本身。这是一种情况。word
,识别所有连续的相同字符的序列。> 1
,则它可以被还原(即长度减 1)。k
,则总的不同原始字符串数量为 k + 1
。count = 1
(对应不还原的情况)。word
,记录当前连续字符的长度。> 1
,则 count += 1
(因为可以还原一次)。> 1
的连续字符序列,可以还原的次数是 length - 1
(但每次只能选择一个还原,因此每个序列贡献 1
到 count
)。> 1
,则可以贡献 1
到 count
(因为可以选择是否还原该序列中的某个重复字符,但只能选一个)。n
的连续序列,可以还原的位置是 n-1
个(即选择哪个重复的字符被去掉)。但题目要求最多一次还原,因此可以选择其中一个位置还原,或者不还原。> 1
,则贡献 n-1
种还原方式。给定的代码 possibleStringCount
的逻辑:
ans = 1
(不还原的情况)。word
,检查 word[i-1] == word[i]
:ans++
。n
个相同字符,有 n-1
个位置可以还原(即 ans += n-1
)。ans++
是在每次连续时增加,因此对于连续 n
个字符,ans
会增加 n-1
次。ans
从 1 开始,i=1
时 word[0] == word[1]
,ans++
→ 2。ans=1
,i=1
:ans=2
,i=2
:ans=3
→ 总共增加 2。ans
的值为 1 + sum over all consecutive sequences (length - 1)
。O(n)
,其中 n
是 word
的长度。我们只需要遍历字符串一次。O(1)
,只使用了常数级别的额外空间(几个变量)。package main
import (
"fmt"
)
func possibleStringCount(word string)int {
ans := 1
for i := 1; i < len(word); i++ {
if word[i-1] == word[i] {
ans++
}
}
return ans
}
func main() {
word := "abbcccc"
result := possibleStringCount(word)
fmt.Println(result)
}
# -*-coding:utf-8-*-
def possible_string_count(word: str) -> int:
ans = 1
for i in range(1, len(word)):
if word[i - 1] == word[i]:
ans += 1
return ans
if __name__ == "__main__":
word = "abbcccc"
result = possible_string_count(word)
print(result)
fn possible_string_count(word: &str) ->usize {
letmut ans = 1;
letbytes = word.as_bytes();
foriin1..bytes.len() {
if bytes[i - 1] == bytes[i] {
ans += 1;
}
}
ans
}
fnmain() {
letword = "abbcccc";
letresult = possible_string_count(word);
println!("{}", result);
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有