标签:
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.
Given the string = "abcdzdcab"
, return "cdzdc"
.
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
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5332514.html