简体   繁体   中英

longest palindromic substring convert Java to Javascript

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"));

Print: bb

And the code will be accepted. But when I convert Java code to JavaScript code, it failed.

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

Why JS code return "cbb" instead of "bb"?

This has to do with the differences between Java's integer division and Javascript's floating-point version.

Replacing this:

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

with this:

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

should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM