[Leetcode] 5-longest palindromic Substring

Source: Internet
Author: User

Title Link: https://oj.leetcode.com/problems/longest-palindromic-substring/


This problem can usually be written out of 2 kinds of practice.

1. Keep an index from the go back sweep, each index cycle, keep left and right index to sweep on both sides, but there are 2 cases, ABA and ABBA. Left and right scan to sweep 2 times

2. DP procedure, 2-D matrix

* Can be properly reduced, such as the current index is completely impossible to provide than the longest string has been obtained longer than possible, then move to the next index


Class Solution {Public:string Longestpalindrome (string s) {if (s.size () = = 0) return "";        int idx = 0;        int maxlen = 0;                string res; while (IDX < s.size ()) {//break if even the longest palindrome string we could get//is still                        Shorter than the Maximun one we have an if (min (s.size ()-idx, IDX + 1) * 2 <= maxlen) break;            int left;                        int right;            1st case, Ex:aba left = idx;            right = IDX; while (left >= 0 && right < S.size ()) {if (s[left] = = S[right]) {if (max                        Len < Right-left + 1) {MaxLen = right-left + 1;                    res = S.substr (left, right-left + 1);                    }--left;                ++right;                } else {break;          }            }              2nd case, Ex:abba left = idx;            right = idx + 1; while (left >= 0 && right < S.size ()) {if (s[left] = = S[right]) {if (max                        Len < Right-left + 1) {MaxLen = right-left + 1;                    res = S.substr (left, right-left + 1);                    }--left;                ++right;                } else {break;        }} ++idx;    } return res; }};


[Leetcode] 5-longest palindromic Substring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.