Longest Palindromic Substring

hard Strings

Problem

Read one word. Print its longest palindromic substring. If several have the same length, print the one that starts first.

Constraints

  • 1 <= length <= 2000, ASCII, no spaces

Examples

Input

babad

Output

bab

Solutions

Best approachTime O(n^2)Space O(1)

A palindrome mirrors around its centre. There are 2n - 1 centres. For each centre we expand while both sides are equal. This needs O(n^2) time but no extra memory.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process one line of text.
 * Input   : One line of text.
 * Output  : The longest palindrome.
 * Approach: Expand around centres.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 1: The best palindrome is stored as start and end (end is not included).
        int bestStart = 0;
        int bestEnd = 1;

        // Step 2: Every palindrome has a centre. The centre is one letter or the gap between two letters.
        for (int centre = 0; centre < s.length(); centre++) {
            for (int type = 0; type < 2; type++) {
                int left = centre;
                int right = centre + type;

                // Step 3: Expand to both sides while the letters are equal.
                while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
                    left--;
                    right++;
                }

                // Step 4: Keep the palindrome if it is longer than the best one (equal length keeps the first).
                if (right - left - 1 > bestEnd - bestStart) {
                    bestStart = left + 1;
                    bestEnd = right;
                }
            }
        }
        return s.substring(bestStart, bestEnd);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. How many centres does a word of length n have?