DEV Community

Cover image for Leetcode 5 - Longest Palindromic Substring
Rohith V
Rohith V

Posted on

2

Leetcode 5 - Longest Palindromic Substring

Problem Statement

Given a string s, return the longest palindromic substring in s.

Test Cases

Example 1:

Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

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

Input: s = "a"
Output: "a"
Example 4:

Input: s = "ac"
Output: "a"

Constraints

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

Code

class Solution {
    private int resultStart;
    private int resultLength;
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        if (s.length() == 1)
            return s;
        int length = s.length();
        for (int start=0; start<length-1; start++) {
            widerange(s, start, start);
            widerange(s, start, start+1);
        }
        return s.substring(resultStart, resultStart + resultLength);
    }

    public void widerange(String s, int start, int end) {
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            start -= 1;
            end += 1;
        }
        if (resultLength < end - start - 1) {
            resultLength = end - start - 1;
            resultStart = start + 1;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

GitHub logo Rohithv07 / LeetCode

LeetCode problems that are solved.

LeetCode

LeetCode problems that are solved.

  • take the bit of the ith(from right) digit:

    bit = (mask >> i) & 1;

  • set the ith digit to 1: mask = mask | (1 << i);

  • set the ith digit to 0: mask = mask & (~(1 << i));

A Sample Structure




Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
divide_r_conquer profile image
Yuehui Ruan

Cool!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more