# Leetcode No.5 longest palindromic Substring

Source: Internet
Author: User

Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.

The longest palindrome string.

There are two ways of thinking:

1, from left to right to find the symmetry point, from the symmetry point (or two identical adjacent characters) to the side of the search, note the maximum length of the search.

2, set a two-dimensional bool array, a[i, j] = TRUE to indicate that the string from I to J is a palindrome string.

So first of all a[i, I] set to true (that is, the length of 1, is a palindrome), and then linearly look for the same character (2-length palindrome), if there is a a[i, i + 1] set to true.

Starting from the length of 3, judge the tail, if the same and a[i+1, j-1] = = TRUE (that is, the rest is a palindrome), then this substring is a palindrome string.

I used the second method. The code is as follows.

`BOOLtab[ +][ +]; stringLongestpalindrome (strings) {stringMax; intn =s.size (); if(n = =0|| n = =1)            returns;  for(inti =0; I < n; i++) Tab[i][i]=true;  for(inti =0; I < n-1; i++) {            if(S[i] = = S[i +1]) {max= S.substr (I,2); Tab[i][i+1] =true; }        }         for(intK =3; K <= N; k++) {             for(inti =0; I < N-k +1; i++) {                intj = i + K-1; if(Tab[i +1][j-1] && s[i] = =S[j]) {Tab[i][j]=true; if(k >max.size ()) Max=S.substr (i, k); }            }        }        returnMax; }`

Two methods if I'm not mistaken, it should all be squared-level complexity.

Do not paste the running time, because the same code submitted two times a lot of time difference, can not explain the problem. But the idea is worth keeping track of.

Leetcode No.5 longest palindromic Substring

Related Keywords:

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.