Need help, i'm new to rust, and trying to exploring rust

I just started to learn rust few month ago.
i need help with this fn that i created, need to return palindrome word from the input.
my question,

  1. is my code right? because when i run it, it just stuck.
  2. is there better way to make this much simple than it is right now ?

fn main() {
let input = "babad";

println!("{:?}", palindrome_substring(input));

}

fn palindrome_substring(s: &str) -> Vec {
let mut s_vec: Vec<_> = s.chars().collect();
let mut result = Vec::new();

let first_index = 0;
let last_index = s_vec.len() - 1;

while first_index < last_index {
    if s_vec[first_index] != s_vec[first_index + 1] && s_vec[first_index] == s_vec[first_index + 2] {
        result.push(s_vec[first_index]);
        result.push(s_vec[first_index + 1]);
        result.push(s_vec[first_index + 2]);
    } else if s_vec[first_index] == s_vec[first_index + 1] {
        result.push(s_vec[first_index]);
        result.push(s_vec[first_index + 1]);
    } else {
        println!("There is no palindrome subsring in the Input")
    }
} 

result

}

Please read the pinned code formatting guide.


In your loop:

    while first_index < last_index {
        // ...
    }

You never return from the function, break out of the loop, or modify first_index or last_index. So if you ever enter the loop,[1] there's no way for you to exit the loop -- the loop will run forever, doing the same thing each time.[2]

You're also only checking for palindromic substrings of length 2 or 3. You'll also panic if the input is too short (you assume that first_index + 2 is in bounds).

These are all flaws in your algorithm, and not really Rust specific notes.


  1. and don't panic (see below) ↩︎

  2. If that's pushing into the Vec, you'll eventually run out of memory and cause a panic that way. ↩︎

1 Like