Option的连续相等字符的最长子串.但是,我的尝试产生了一个编译器错误: pub fn longest_sequence(s: &str) -> -6ren">
gpt4 book ai didi

string - 查找连续相等字符的最长子串时出现 "borrowed value does not live long enough"错误如何处理?

转载 作者:行者123 更新时间:2023-11-29 08:24:18 24 4
gpt4 key购买 nike

我有一篇作业求出签名为fn(s: &str) -> Option<&str>的连续相等字符的最长子串.但是,我的尝试产生了一个编译器错误:

pub fn longest_sequence(s: &str) -> Option<&str> {
let s_len = s.len();
if s_len == 0 {
return None
}
let mut cur_char = s.chars().nth(0);
let mut cur_occ = 0;
let mut max_char = s.chars().nth(0);
let mut max_occ = 0;

for i in 0..s_len {
let c = s.chars().nth(i);
if c == cur_char {
cur_occ = cur_occ + 1;
} else {
if cur_occ > max_occ {
max_occ = cur_occ;
max_char = cur_char;
}
cur_char = c.clone();
cur_occ = 1;
}
}
if cur_occ > max_occ {
max_occ = cur_occ;
max_char = cur_char;
}
let cr = max_char.unwrap();
let charstr = cr.to_string();
let string = charstr.repeat(max_occ);
let strr = string.as_str();
let some = Some(strr.clone());
println!("in {:?}",some);
some // Compilation error
// None // if returning None, then it compiles and runs as expected
}

fn main () {
println!("out {:?}",longest_sequence(&"aaabbbcccc"));
}
error[E0597]: `string` does not live long enough
--> r.rs:31:16
|
31 | let strr = string.as_str();
| ^^^^^^ borrowed value does not live long enough
...
35 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 1:1...
--> r.rs:1:1
|
1 | / pub fn longest_sequence(s: &str) -> Option<&str> {
2 | | let s_len = s.len();
3 | | if s_len == 0 {
4 | | return None
... |
34 | | some
35 | | }
| |_^

如果我返回 None而不是 some ,代码编译并且输出如您所料:

in Some("cccc")
out None

我怎样才能使这项工作?有人可以帮助我理解这个问题吗?

最佳答案

我认为如果您在传入的字符串中跟踪索引然后返回该字符串的一部分,这会更有意义:

s.get(start_index..stop_index)

Rust 使这有点棘手,因为您需要正确索引 utf-8 字符的字节,但您不仅想要最长的字节串,还想要最长的字符。

不过,我认为这样做更容易理解也更清晰:跟踪当前最长序列的长度以及开始和停止字节。保留当前字符运行的字符计数,然后使用 get() 返回切片。这避免了在函数中创建新字符串的问题。

pub fn longest_sequence(s: &str) -> Option<&str> {
if s.is_empty() {
return None
}

let mut chars = s.char_indices();
let (mut char_start, mut curr) = chars.next().unwrap(); // get initial character
let mut longest = (char_start,curr.len_utf8(), 1); // (start(byte), stop(byte), len(characters)
let mut curr_char_count = 1; // number of chars in current run

for (idx, c) in chars {
match c {
c if c == curr => {
curr_char_count += 1;
if curr_char_count > longest.2 {
longest = (char_start, idx + c.len_utf8(), curr_char_count);
}
}
n => {
curr = n;
curr_char_count = 1;
char_start = idx;
}
}
}
s.get(longest.0..longest.1)
}

这将允许非 ascii 字符串工作并仍然返回原始字符串的一部分:

fn main() {     
let s= longest_sequence("BB💣💣💣💣mmm!");
println!("{:?}", s);

// Some("💣💣💣💣")
}

关于string - 查找连续相等字符的最长子串时出现 "borrowed value does not live long enough"错误如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com