LeetCode刷题:5. 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:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

 

Example:

Input: "cbbd"

Output: "bb"


思路:

采用简单暴力的遍历搜索方式,分析题目的回文形式,可分为两种:单数回文和双数回文。在遍历的过程中,不断进行回文检测,更新最大的回文子串的长度,记录相应的索引。


代码:

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

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

	Example:
	Input: "cbbd"
	Output: "bb"
*/

#include <string>

using namespace std;

class Solution {
	// 回文检测算法函数
	void longestPalindrome(const string& s, int a, int b, int& start, int& last)
	{
		// 字符串总长度
		int len = s.size();

		// 在起始索引处向两侧扩张地检测索引
		while (a >= 0 && b < len && s[a] == s[b])
		{
			a--;
			b++;
		}

		// 将回文的索引设置为正确的位置
		a++;
		b--;

		// 如果当前的回文长度大于历史回文长度,则更换回文子串前后索引
		if (b - a > last - start)
		{
			start = a;
			last = b;
		}
	}
	

public:
	string longestPalindrome(string s) {
		// 字符串总长度
		int len = s.size();

		// 判断若为空串,直接返回此空串
		if (len == 0)
			return s;

		// 创建回文的起始和终止索引
		int start = 0, last = 0;

		// 一次遍历
		for (int i = 0; i < len - 1; i++)
		{
			// 单数的回文长度检测
			longestPalindrome(s, i, i, start, last);

			// 双数的回文长度检测
			longestPalindrome(s, i, i + 1, start, last);

		}

		//返回回文字符串
		return s.substr(start, last - start + 1);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值