gpt4 book ai didi

indexing - 检查字符串是否旋转时超出范围

转载 作者:行者123 更新时间:2023-12-03 11:41:27 24 4
gpt4 key购买 nike

// This function checks if two string are rotation of itself
//
// #Arguments
//
// 'str1' - a str type reference to store one string to check
// 'str2' - a str type reference to store other string to check
//
// #Return
//
// Return a bool value denoting if the string are rotation of each other

pub fn is_rotation(str1: &str, str2: &str) -> bool {
let len1 = str1.len();
let len2 = str2.len();

let string1: Vec<char> = str1.chars().collect();
let string2: Vec<char> = str2.chars().collect();

if len1 != len2 {
return false;
}

let mut longest_prefix_suffix = vec![0, len1];
let mut prev_len = 0;
let mut i = 1;

while i < len1 {
if string1[i] == string2[prev_len] {
prev_len += 1;
longest_prefix_suffix[i] = prev_len;
i += 1;
} else if prev_len == 0 {
longest_prefix_suffix[i] = 0;
i += 1;
} else {
prev_len = longest_prefix_suffix[prev_len - 1];
}
}

i = 0;

let mut k = longest_prefix_suffix[len1 - 1];

while k < len2 {
if string2[k] != string1[i] {
return false;
}
i += 1;
k += 1;
}

true
}
运行代码时,出现以下错误:
thread 'main' panicked at 'index out of bounds: the len is 2 but the index is 2', src/rotation.rs:29:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
我该如何解决?

最佳答案

好像有longest_prefix_suffix的错字。我假设您打算编写以下内容:

let mut longest_prefix_suffix = vec![0; len1];
注意 ;0之间的 len1,的使用创建了具有两个元素的 Vec

另外,一种更简单的方法可能是以下方法:
fn is_rotation(s1: &str, s2: &str) -> bool {
if s1.len() != s2.len() {
return false;
}

s1.repeat(2).contains(&s2)
}

assert!(is_rotation("hello", "ohell") // true
assert!(is_rotation("hello", "olleh") // false

关于indexing - 检查字符串是否旋转时超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66499047/

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