銆怢eetCode銆?. Longest Palindromic Substring
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了銆怢eetCode銆?. Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/string' title='string'>string
log code link inpu longest max bst privateDifficulty: Medium
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
Intuition
浠庝笅鏍?寮€濮嬪線鏈熬閬嶅巻锛屽垽鏂互绗琲涓瓧绗︿负涓績锛屼互鍙婁互绗琲鍜岀i+1涓瓧绗︿箣闂翠负涓績鐨勬儏鍐碉紝鏍规嵁涓よ竟瀛楃鐩哥瓑鐨勬儏鍐佃繘琛宔xpand锛屼粠鑰岀‘瀹氭渶闀垮洖鏂囧瓙涓层€?/p>
Solution
public String longestPalindrome(String s) { if(s==null || s.length()<=0) return s; int start=0; int end=0; for(int i=0;i<s.length();i++){ int len1=expand(s,i,i); int len2=expand(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 expand(String s,int l,int r){ while(l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)){ l--; r++; } return r-l-1; }
銆€銆€
Complexity
Time complexity : O(n^2)
銆€銆€闇€瑕侀亶鍘唍涓瓧绗︼紝姣忔鍒ゆ柇鐨勫鏉傚害涓篛(n)銆?/p>
Space complexity : O(1)
What I鈥榲e learned
1. 鍥炴枃瀛楃涓诧紝鎵惧埌涓績锛屽線宸﹀彸涓よ竟杩涜鍒ゆ柇銆?/p>
以上是关于銆怢eetCode銆?. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章