Leetcode_DP(level_M)_647_PalindromicSubstrings

本文深入探讨了两种高效算法,用于找出字符串中所有回文子串。通过二维和一维状态压缩的方法,详细解析了状态定义、转换方程及其实现代码,为读者提供了理解和实现回文子串检测的清晰路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Thinking

  • Plan A (Two-dimensional, from top to bottom)
  • State: dp[i][j] denotes whether the substring whose indices from i to j is a palindrom.
  • Transformation equation : dp[i][j] = true if dp[i+1][j-1].

  • Plan B (One-dimensional, state compression, from bottom to top)
  • State: dp[i] denotes whether the substring whose indices from j to i is a palindrom (j = {0…i}).
  • Transformation equation : dp[j] = true if dp[j+1]

Code

  • Plan A
int countSubstrings(string s) {
        int size = s.length();
        vector< vector<int> > dp (size, vector<int>(size, 0));
     
        // diagonal
        int count = size;
        for (int i=0; i<size; i++) {
        	dp[i][i] = 1;
		}
		
        for (int i=size-1; i>=0; i--) {
            for (int j=i; j<size; j++) {
                if (i != j && s[i] == s[j]) {   // s[i] == s[j]
                	if (i+1 == j || dp[i+1][j-1]) {
						dp[i][j] = 1;
                    	count++;
					}
                }
            }
        }
        
        return count;
    }

Plan B

int countSubstrings(string s) {
        int size = s.length();
        int* dp = new int[size]();
        
        int count = 0;
        for (int i=0; i<size; i++) {
            
            dp[i] = 1;
            count++;
            
            for (int j=0; j<i; j++) {
                if (s[i] == s[j] && dp[j+1]) {
                    dp[j] = 1;
                    count++;
                } else {
                    dp[j] = 0;
                }
            }
        }
        
        return count;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值