https://leetcode.com/problems/longest-palindromic-substring/

public String longestPalindromeExpandAroundCenter(String s) {
        if (s == null || s.length() < 1) return "";
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private int expandAroundCenter(String s, int left, int right) {
        int L = left, R = right;
        while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
            L--;
            R++;
        }
        return R - L - 1;
    }

System.out.println(新的LongestPalinSubstring().longestpalindromexpandaroundcenter(“cbbd”));
打印:bb
代码将被接受但是当我将java代码转换成javascript代码时,它失败了。
var longestPalindrome = function (s) {
    if (s == null || s.length < 1) return "";
    var start = 0, end = 0;
    for (var i = 0; i < s.length; i++) {
        var len1 = expandAroundCenter(s, i, i);
        var len2 = expandAroundCenter(s, i, i + 1);
        var len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
};
var expandAroundCenter = function (s, left, right) {
    var L = left, R = right;
    while (L >= 0 && R < s.length && s[L] == s[R]) {
        L--;
        R++;
    }
    return R - L - 1;
}

log(longestpalindrome(“cbbd”))
CBB
为什么JS代码返回“cbb”而不是“bb”?

最佳答案

这与Java的整数除法和Javascript的浮点版本之间的差异有关。
替换为:

        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }

有了这个:
        if (len > end - start) {
            start = i - Math.floor((len - 1) / 2);
            end = i + Math.floor(len / 2);
        }

应该会修好的。

10-06 08:34