最长回文子串将Java转换为Javascript

时间:2019-06-18 18:09:21

标签: javascript java algorithm

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(new LongestPalinSubstring()。longestPalindromeExpandAroundCenter(“ 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;
}

console.log(longestPalindrome(“ cbbd”))

cbb

为什么JS代码返回“ cbb”而不是“ bb”?

1 个答案:

答案 0 :(得分:2)

这与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);
        }

应该修复它。