LeetCode——5.Longest Palindromic Substring

1.题目详情

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给出一个字符串s,找到s中最长的一个回文串。可以假设s的最大长度为1000。

Example 1:

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

Example 2:

Input: “cbbd”
Output: “bb”

完善下面的代码:

class Solution {
public:
    string longestPalindrome(string s) {
        
    }
};

2.解题方法

回文串是指一个字符串的反转字符串还是和原来的一样,比如"aba"和"abba",即从中间看回文串是对称的。所以这里的解题思路就是从回文串的中间这一关键点落手。遍历字符串s,从每一处字符开始往两边看,找到以这处字符为中心的回文串。当然还要考虑特殊情况,像上面的"abba"的中间的两个’b’一样。

class Solution {
public:
	 string longestPalindrome(string s) {
		 int size = s.size();
		 int start = 0;
		 int maxLength = 0;
		 string maxLengthStr;
		 while (start < size) {
		 	int left = start - 1;
		 	int right = start + 1;
		 	int length = 1;
		 	while (s[left] == s[right] && left >= 0 && right < size) {
		 		length = length + 2;
		 		left = left - 1;
		 		right = right + 1;
		 	}
		 	if (length > maxLength) {
		 		maxLength = length;
		 		maxLengthStr = s.substr(left + 1, right - left - 1);
		 	}
		 	length = 0;
		 	left = start;
		 	right = start + 1;
		 	while (s[left] == s[right] && left >= 0 && right < size) {
		 		length = length + 2;
		 		left = left - 1;
		 		right = right + 1;
		 	}
		 	if (length > maxLength) {
		 		maxLength = length;
		 		maxLengthStr = s.substr(left + 1, right - left - 1);
		 	}
		 	start = start + 1;
		 }
		 return maxLengthStr;
	 }
};

最终运行时间是8ms。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值