Algorithm


Given a string s, return the longest palindromic substring (A substring is a contiguous non-empty sequence of characters within a string.) in s.

Example 1:

 

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

 

Example 2:

 

Input: s = "cbbd"
Output: "bb"

 

Constraints:

 

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


char* longestPalindrome(char* s) {
    int sz;
    int i, j, k, l;
    int where = 0, len = 0;
    
    if (!s || !*s) return s;
    
    sz = strlen(s);

    for (i = 0, j = 0, k = 0; len  <  (sz - k) * 2; i = k, j = k) {
        while (j + 1 < sz && s[j] == s[j + 1]) {
            j ++;  // skip all repeating characters
        }
        k = j + 1; // where to start next try
        while (i > 0 && j + 1  <  sz && s[i - 1] == s[j + 1]) {
            i --;  // expand dual direction
            j ++;
        }
        l = j - i + 1; // what we have fond so far
        if (len  <  l) {
            len = l;
            where = i;
        }
    }
    s = s + where;
    s[len] = 0;
    return s;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "cbbd"

Output

x
+
cmd
"bb"

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
	string longestPalindrome(string s) {
		if (s.size() == 0 || s.size() == 1) return s;
		string res;
		int maxlen = 0;
		for (int i = 0; i  <  s.size() - maxlen; i++) {
			for (int j = s.size() - 1; j >= i + maxlen; j--) {
				if (s[j] != s[i]) continue;
				string str = s.substr(i, j - i + 1);
				if (isPalindrome(str) && str.size() > maxlen) {
					maxlen = str.size();
					res = str;
				}
			}
		}
		return res;
	}

	bool isPalindrome(string s) {
		if (s.size() == 0 || s.size() == 1) return true;
		int i(0), j(s.size() - 1);
		while (s[i] == s[j] && i  <  j) i++, j--;
		return i >= j;
	}
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "babad"

Output

x
+
cmd
"bab"

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String longestPalindrome(String s) {
    int start = 0;
    int end = 0;
    for (int i = 0; i  <  s.length(); i++) {
      int lenOne = helper(s, i, i);
      int lenTwo = helper(s, i, i + 1);
      int maxLength = Math.max(lenOne, lenTwo);
      if (maxLength > end - start) {
        start = i - (maxLength - 1) / 2;
        end = i + maxLength / 2;
      }
    }
    return s.substring(start, end + 1);
  }
  
  private int helper(String s, int left, int right) {
    while (left >= 0 && right  <  s.length() && s.charAt(left) == s.charAt(right)) {
      left--;
      right++;
    }
    return right - left - 1;
  }
}
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


const longestPalindrome = function(s) {
  let res = ''
  for(let i = 0, len = s.length; i  <  len; i++) {
    let s1 = chk(s,i,i), s2 = chk(s,i,i+1)
    if(s1.length > res.length) res = s1
    if(s2.length > res.length) res = s2
  }
  return res
};

function chk(s, i, j) {
  for(; i>= 0 && j < s.length; i--, j++) {
    if(s[i] !== s[j]) break
  }
  return s.slice(i+1, j>
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "cbbd"

Output

x
+
cmd
"bb"

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def longestPalindrome(self, s: str) -> str:
        def check(l, r):
            while 0 <= l <= r < len(s) and s[l] == s[r]:
                l -= 1
                r += 1
            return s[l + 1:r]
        pals = [check(i, i) for i in range(len(s))] + [check(i, i + 1) for i in range(len(s) - 1) if s[i] == s[i + 1]]
        return sorted(pals, key = len)[-1] if pals else ''
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "babad"

Output

x
+
cmd
"bab"

#6 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _005_LongestPalindromicSubstring
    {
        public string LongestPalindrome(string s)
        {
            if (string.IsNullOrWhiteSpace(s) || s.Length == 1) return s;

            int n2 = s.Length * 2 + 1;
            var s2 = new char[n2];
            for (int i = 0; i  <  s.Length; i++)
            {
                s2[i * 2] = '#';
                s2[i * 2 + 1] = s[i];
            }
            s2[n2 - 1] = '#';

            var p = new int[n2];
            int rangeMax = 0, center = 0;
            var longestCenter = 0;

            for (int i = 1; i  <  n2 - 1; i++)
            {
                if (rangeMax > i)
                    p[i] = Math.Min(p[center * 2 - i], rangeMax - i);

                while (i - 1 - p[i] >= 0 && i + 1 + p[i]  <  n2 && s2[i - 1 - p[i]] == s2[i + 1 + p[i]])
                    p[i]++;

                if (i + p[i] > rangeMax)
                {
                    center = i;
                    rangeMax = i + p[i];
                }

                if (p[i] > p[longestCenter])
                    longestCenter = i;
            }

            var range = p[longestCenter];
            return s.Substring((longestCenter - range) / 2, range);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "cbbd"

Output

x
+
cmd
"bb"
Advertisements

Demonstration


Previous
#04 Leetcode Median of Two Sorted Arrays Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#06 Leetcode Zigzag Conversion Solution in C, C++, Java, JavaScript, Python, C# Leetcode