LeetCode Algorithm 0005 - Longest Palindromic Substring (Medium)

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/darkrabbit/article/details/82723472

LeetCode Algorithm 0005 - Longest Palindromic Substring (Medium)

Problem Link: https://leetcode.com/problems/longest-palindromic-substring/description/


Description

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"

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/longest-palindromic-substring/description/

namespace P5LongestPalindromicSubstring
{
    class Solution
    {
        public:
        string longestPalindrome(string s)
        {
            // 最开始看题目时, 不知道什么是`palindromic`,写了一些错误代码。
            // Palindromic Substring:是指正读和反读都一样的字符串。

            if (s.empty())
            {
                return "";
            }

            int start = 0;
            int len = 0;

            for (size_t i = 0; i < s.size(); i++)
            {
                int len1 = GetPalindromicLen(s, i, i);
                int len2 = GetPalindromicLen(s, i, i + 1);

                if (len1 > len)
                {
                    start = i - len1 / 2;
                    len = len1;
                }

                if (len2 > len)
                {
                    start = i + 1 - len2 / 2;
                    len = len2;
                }
            }

            return s.substr(start, len);
        }

        private:
        int GetPalindromicLen(string s, int leftIndex, int rightIndex)
        {
            int len = 0;

            for (leftIndex, rightIndex; leftIndex >= 0 && rightIndex < s.size(); leftIndex--, rightIndex++)
            {
                if (s[leftIndex] != s[rightIndex])
                {
                    break;
                }

                len = rightIndex - leftIndex + 1;
            }

            return len;
        }
    };
}

猜你喜欢

转载自blog.csdn.net/darkrabbit/article/details/82723472