Longest Palindromic Substring in Rust

impl Solution {
    // A function to check if a string is a palindrome
    fn is_palindrome(s: &str) -> bool {
        // Use two pointers to compare the characters from both ends
        let mut left = 0;
        let mut right = s.len() - 1;
        // Convert the string to a vector of bytes for easier indexing
        let bytes = s.as_bytes();
        while left < right {
            // If the characters are not equal, return false
            if bytes[left] != bytes[right] {
                return false;
            }
            // Move the pointers closer to the center
            left += 1;
            right -= 1;
        }
        // If the loop finishes, the string is a palindrome
        return true;
    }

    // A function to return the longest palindromic substring in a string
    fn longest_palindrome(s: String) -> String {
        // If the string is empty or has only one character, return the string itself
        if s.len() <= 1 {
            return s;
        }
        // Initialize the longest palindrome as the first character
        let mut longest = s[0..1].to_string();
        // Loop through the string and check every substring
        for i in 0..s.len() {
            for j in i + 1..s.len() {
                // Get the substring from i to j
                let sub = s[i..j + 1].to_string();
                // If the substring is longer than the current longest and is a palindrome, update the longest
                if sub.len() > longest.len() && Solution::is_palindrome(&sub) {
                    longest = sub;
                }
            }
        }
        // Return the longest palindrome
        return longest;
    }
}

PrevNext