[LeetCode] Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

以下说明转载自:

https://leetcode.com/problems/longest-palindromic-substring/discuss/147548/Direct-c%2B%2B-DP

My code is based on the solution Approach3.

First initialize a matrix P, which is used to store if the substring is palindromic. Now we should fill the block of "S(i) = S(i)" and "S(i) = S(i+1)", the basic case that we can't find any substring in it. Then with this matrix, we can decide if a string is palindromic by if its substring is palindromic and if its start letter equals end letter.

The image below is a matrix for string "abbc". For example, start with the first "b" and end with "c" tells if substring "bbc" is palindromic. What we need to do next is filling the "??" block, only half of the matrix is used.
image

 

After initialization, we can decide if a string is palindromic by its substring and newly added letters, shown below.
image
If we want to decide the block pointed by the arrow("abb"), we should look up [b,b], which is substring "b", and see if ("a"=="b"). As shown, "a"!="b", so "abb" is not palindromic.

After that, it seems like this:
image

 

Last, we have got this matrix, but we still need to find which is the longest palindromic substring.
My method is only traversing it, return the longest substring. So the result in this example is "bb".

 

class Solution {
public:
	string longestPalindrome(string s) {
		int len = s.size();
		if (len == 0) return "";
		bool** symbol = new bool*[len];
		for (int i = 0; i < len; i++)
			symbol[i] = new bool[len];
		for (int i = 0; i < len; i++)
			for (int j = 0; j < len; j++)
				symbol[i][j] = false;
		// initialize symbol[len][len]
		for (int i = 0; i < len; i++) {
			symbol[i][i] = true;
			if (i == len - 1) break;
			symbol[i][i+1] = (s[i] == s[i+1]);
		}
		
		// dynamic programming
		for (int i = len - 2; i >= 0; i--) {
			int start = i + 2;
			for (int j = start; j < len; j++) {
				symbol[i][j] = (symbol[i+1][j-1] && s[i] == s[j]);
			}
		}
		
		// get max length string
		int max = 0;
		string maxstr = "";
		for (int i = 0; i < len; i++) {
			int count = 0;
			for (int j = i; j < len; j++) {
				if (symbol[i][j] == true) {
					count = j - i + 1;
				}
			}
			if (count > max) {
				max = count;
				maxstr = s.substr(i, count);
			}
		}
		return maxstr;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值