Allleetcode

#5 Longest Palindromic Substring Leetcode Java | Java Leetcode Problems Solve | java LeetCode solved

Longest Palindromic Substring Leetcode Java | Java Leetcode Problems Solve | java LeetCode solved

5. Longest Palindromic Substring

Given a string s, return the longest 

palindromic

substring 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.

Solution:-

class Solution {
    int start = -1;
    int length = 0;
    public String longestPalindrome(String s) {
        this.start = -1;
        this.length = 0;
        explore(s, s.length() / 2, 0);
        return this.start == -1 ? null : s.substring(this.start, this.start + this.length);
    }

    public void explore(String s, int index, int direction) {
        int i = index - 1;
        int j = index + 1;
        while (i >= 0 && s.charAt(i) == s.charAt(index))
            i--;
        while (j < s.length() && s.charAt(j) == s.charAt(index))
            j++;
        int l = i;
        int r = j;
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l--;
            r++;
        }
        l++;
        if (r - l > length) {
            this.length = r - l;
            this.start = l;
        }
        if (direction != 2 && 2 * (i + 1) > this.length)
            explore(s, i, 1);
        if (direction != 1 && 2 * (s.length() - j) > this.length)
            explore(s, j, 2);
    }
}

Visit For More :- https://softwaretechit.com

HackerRank Problems Solution :- https://softwaretechit.com/category/hackerrank

Blog:- https://blog.softwaretechit.com

Shop:- https://shop.softwaretechit.com

Important Link’s :-https://home.softwaretechit.com

Projects :- https://link.softwaretechit.com


leetcode,java,leetcode java,leetcode problems,leetcode solutions,problems,leetcode problems java,leetcode java solutions,leetcode 1,leetcode problem solving java,problem solving,two sum leetcode,leetcode easy problems,leetcode problems solve,leetcode solved problems,leetcode google problems,how to use leetcode effectively,solving leetcode problems,leetcode two sum,leetcode preparation,leetcode beginner problems,java leetcode #softwaretechit #2023 #tech

Leave a ReplyCancel reply

Exit mobile version