算法分析与设计——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"

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

思路

       遍历字母,以每一个字母为中心,同时遍历前后相对应的字母,判断是否相等。如果不相等则停止遍历。但是这样只能找出aba这样的,找不出abba,abbbba这样的,所以在前面先用两个while循环将所有与中心相同的字母包含进来。

代码

class Solution {
public:
    string longestPalindrome(string s) {
        int size = s.size();
        if (size <= 1) {
            return s;
        }
        int start = 0, max = 1;
        for (int i = 1; i < size; i++) {
            int start_ = i-1, end_ = i+1;
            int current = 1;
            while (start_ >= 0 && s[start_] == s[i]) {//忽略所有相同的字母,如aaa,aa
                start_--;
                current++;
            }
            while (end_ <= size && s[end_] == s[i]) {//忽略相同字母
                end_++;
                current++;
            }
            while (start_ >= 0 && end_ >= 0) {
                if (s[start_] == s[end_]) {
                    start_--;
                    end_++;
                    current += 2;
                } else {
                    start_++;
                    break;
                }
            }
            if (start_ < 0) {//避免aa这样的字符串使start_小于0
                start_++;
            }
            if (current > max) {
                max = current;
                start = start_;
            }
        }
        return s.substr(start, max);
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值