动态规划

LeetCode:5. longest Palindrom substring

第一种方法:
Approach 4: Expand Around Center
In fact, we could solve it in O(n^2)O(n
2
) time using only constant space.

We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 12n−1 such centers.

You might be asking why there are 2n - 12n−1 but not nn centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as “abba”) and its center are between the two 'b’s.

实现:

class Solution {
public:
	string longestPalindrome(string s) {
		int m = 0, start = 0, end = 0;
		for (int i = 0; i < s.length(); i++) {
			int len1 = expandCenter(s, i, i);
			int len2 = expandCenter(s, i, i + 1);
			int len = max(len1, len2);
			if (len > m) {
				m = len;
				start = i - (len - 1) / 2;
			}
		}
		return s.substr(start, m);
	}
	int expandCenter(string s, int left, int right) {
		while (left >= 0 && right < s.length() && s[left] == s[right]) {
			left--;
			right++;
		}
		return right - left - 1;
	}
};

Success
Details
Runtime: 40 ms, faster than 57.91% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 104 MB, less than 17.80% of C++ online submissions for Longest Palindromic Substring.

注意:对substr()函数的理解,第一个参数是start,第二个是size。

但是速度还是不够快,所以我决定学习一下动态规划的思想。
这是个很有启发性的博客:
https://blog.youkuaiyun.com/u013309870/article/details/75193592
过桥问题的理解可以参考这篇文章:https://blog.youkuaiyun.com/u014113686/article/details/82464635

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值