Snippets

Radistao A LongestPalindromicSubstring

Created by Radistao A last modified
// https://leetcode.com/problems/longest-palindromic-substring/submissions/

public class LongestPalindromicSubstring {

    public String longestPalindrome(String s) {
        final var bytes = s.getBytes();
        var maxI = 0;
        var maxL = 1;
        for (int i = 0; i < bytes.length; i++) {
            for (int j = bytes.length; j > i; j--) {
                if (isPalindrome(bytes, i, j) && j - i > maxL) {
                    maxL = j - i;
                    maxI = i;
                }
            }
        }
        return new String(bytes, maxI, maxL, java.nio.charset.StandardCharsets.ISO_8859_1);
    }

    private boolean isPalindrome(byte[] bytes, int i, int j) {
        for (; i < j; i++, j--) {
            if (bytes[i] != bytes[j - 1]) {
                return false;
            }
        }
        return true;
    }
}
public class LongestPalindromicSubstring {
    public String longestPalindrome(String s) {
        char[] chars = s.toCharArray();

        int maxLength = 0;
        int left = 0;
        for (int i = 0; i < chars.length; i++) {
            // event
            int currentLength = findPalindrome(chars, i + 1, i);
            if (currentLength > maxLength) {
                maxLength = currentLength;
                left = i - currentLength / 2 + 1;
            }
            // odd
            currentLength = findPalindrome(chars, i, i);
            if (currentLength > maxLength) {
                maxLength = currentLength;
                left = i - currentLength / 2;
            }
        }

        return new String(chars, left, maxLength);
    }

    private int findPalindrome(char[] chars, int l, int r) {
        while (l > 0 && r < chars.length - 1 && chars[l - 1] == chars[r + 1]) {
            l--;
            r++;
        }
        return r - l + 1;
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.