标签:Palindromic int res Substring Longest Input Output Example 回文
问题
求最长回文子串,即左右对称
Given a string s
, return the longest palindromic substring in s
.
Example 1:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Example 3:
Input: s = "a" Output: "a"
Example 4:
Input: s = "ac" Output: "a"
思路
俩种情况,ab ba和ab b ba
回文串,经典的DP,第[i][j]是否为回文,由[i+1][j-1]&&本身决定(除了*)
*tips: 对角线恒为true,i-j<2时,是否为回文,只由s.i是否等于s.j决定(图中三角形)
代码
*注意循环顺序,因为上下三角本质是一样的,为了更快,只用选其中一个三角
*选了三角后要注意扫的方向,从前往后可能[i+1][j-1]还没被赋值
public static String longestPalindrome(String s) { int n = s.length(); String res = null; boolean[][] dp = new boolean[n][n]; for (int i = n - 1; i >= 0; i--) { for (int j = i; j <n; j++) { dp[i][j] = s.charAt(i) == s.charAt(j) && ((j-i)<2||dp[i + 1][j - 1]); if (dp[i][j] && (res==null|| j - i + 1 > res.length())) { res = s.substring(i, j + 1); } } } return res; }
标签:Palindromic,int,res,Substring,Longest,Input,Output,Example,回文 来源: https://www.cnblogs.com/inku/p/15614235.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。