检查字符串是否旋转时索引越界

时间:2021-03-05 20:13:10

标签: indexing rust

// 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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

看起来 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