Golang solution, 6ms


  • 0
    J
    func longestPalindrome(s string) string {
        maxLen, curLen, i, l := 0, 0, 0, len(s)
    	sub := ""
    	for ; i + maxLen / 2 < l; i++ {
    		j := 1
    		if (s[i - maxLen / 2] == s[i + maxLen / 2] ||
    			(i + maxLen / 2 + 1 < l && s[i - maxLen / 2] == s[i + maxLen / 2 + 1])){
    
    		} else {
    			continue
    		}
    		for curLen = 1; i - j >= 0 && i + j < l; {
    			if (s[i - j] == s[i + j]) {
    				curLen += 2
    				j ++
    			} else {
    				j--
    				break
    			}
    		}
    		if curLen > maxLen {
    			maxLen = curLen
    			if (i - j < 0 || i + j >= l) {
    				j--
    			}
    			sub = s[i - j: i + j + 1]
    		}
    		j = 0
    		for curLen = 0; i - j >= 0 && i + j + 1 < l; {
    			if (s[i - j] == s[i + j + 1]) {
    				curLen += 2
    				j ++
    			} else {
    				j--
    				break
    			}
    		}
    		if (curLen > maxLen) {
    			maxLen = curLen
    			if (i - j < 0 || i + j + 1 >= l) {
    				j--
    			}
    			sub = s[i - j: i + j + 2]
    		}
    	}
    	return sub
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.