DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Leetcode 5 - Longest Palindromic Substring
Rohith V
Rohith V

Posted on

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




Top comments (1)

Collapse
 
divide_r_conquer profile image
Yuehui Ruan

Cool!

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.