All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0131_palindrome_partitioning.Solution.rs Maven / Gradle / Ivy

The newest version!
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Backtracking #Big_O_Time_O(N*2^N)_Space_O(2^N*N)
// #2024_09_09_Time_65_ms_(85.18%)_Space_20.6_MB_(68.52%)

impl Solution {
    pub fn partition(s: String) -> Vec> {
        let mut res = Vec::new();
        let mut curr_arr = Vec::new();
        Self::backtracking(&mut res, &mut curr_arr, &s, 0);
        res
    }

    fn backtracking(res: &mut Vec>, curr_arr: &mut Vec, s: &str, start: usize) {
        if start == s.len() {
            res.push(curr_arr.clone());
            return;
        }
        for end in start..s.len() {
            if !Self::is_palindrome(s, start, end) {
                continue;
            }
            curr_arr.push(s[start..=end].to_string());
            Self::backtracking(res, curr_arr, s, end + 1);
            curr_arr.pop();
        }
    }

    fn is_palindrome(s: &str, mut start: usize, mut end: usize) -> bool {
        while start < end && s.as_bytes()[start] == s.as_bytes()[end] {
            start += 1;
            end -= 1;
        }
        start >= end
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy