lintcode-medium-Longest Palindromic Substring
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
Given a string S
, find the longest palindromic substring in S
. You may assume that the maximum length of S
is 1000, and there exists one unique longest palindromic substring.
Example
Given the string = "abcdzdcab"
, return "cdzdc"
.
Challenge
O(n2) time is acceptable. Can you do it in O(n) time.
n^2做法:
public class Solution { /** * @param s input string * @return the longest palindromic substring */ public String longestPalindrome(String s) { // Write your code here if(s == null || s.length() == 0) return s; String result = s.substring(0, 1); for(int i = 1; i < s.length(); i++){ int left = i; int right = i; while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ left--; right++; } String temp = s.substring(left + 1, right); if(temp.length() > result.length()) result = temp; } for(int i = 0; i < s.length(); i++){ int left = i; int right = i + 1; while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ left--; right++; } String temp = s.substring(left + 1, right); if(temp.length() > result.length()) result = temp; } return result; } }
以上是关于lintcode-medium-Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Longest Palindromic Substring