LeetCode每日一题(1312. Minimum Insertion Steps to Make a String Palindrome)

Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

A Palindrome String is one that reads the same backward as well as forward.

Example 1:

Input: s = “zzazz”
Output: 0

Explanation: The string “zzazz” is already palindrome we don’t need any insertions.

Example 2:

Input: s = “mbadm”
Output: 2

Explanation: String can be “mbdadbm” or “mdbabdm”.

Example 3:

Input: s = “leetcode”
Output: 5

Explanation: Inserting 5 characters the string becomes “leetcodocteel”.

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

看其他朋友的答案,受益良多。



use std::collections::HashMap;

impl Solution {
    fn dp(chars: &Vec<char>, i: usize, j: usize, cache: &mut HashMap<(usize, usize), i32>) -> i32 {
        if i >= j {
            return 0;
        }
        if chars[i] == chars[j] {
            let next = if let Some(c) = cache.get(&(i + 1, j - 1)) {
                *c
            } else {
                Solution::dp(chars, i + 1, j - 1, cache)
            };
            cache.insert((i, j), next);
            return next;
        }
        let left = if let Some(c) = cache.get(&(i + 1, j)) {
            *c
        } else {
            Solution::dp(chars, i + 1, j, cache)
        };
        let right = if let Some(c) = cache.get(&(i, j - 1)) {
            *c
        } else {
            Solution::dp(chars, i, j - 1, cache)
        };
        let ans = left.min(right) + 1;
        cache.insert((i, j), ans);
        ans
    }
    pub fn min_insertions(s: String) -> i32 {
        Solution::dp(&s.chars().collect(), 0, s.len() - 1, &mut HashMap::new())
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值