leetcode5- Longest Palindromic Substring- medium
Posted jasminemzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode5- Longest Palindromic Substring- medium相关的知识,希望对你有一定的参考价值。
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
1. O(n2 * l)复杂度做。双层for循环,每次重新调用这个substring是不是palindrome的方程。
2.O(n2)复杂度做。DP。boolean dp[i][j]定义为s.substring(i, j + 1)是不是回文串。状态转移方程是:dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
细节:1.不用担心i+1, j-1超过范围,因为i,j能进for循环说明满足要求了,而且i比j小,所以i+1最大到j,j-1最小到i,都是合格的。 2.需要担心i+1, j-1之间出现交叉,避免方式就是加上j-i < 3的限制,当两者靠的足够近有交叉的风险的时候你就去人工认可。3.注意最后返回的字符串是s.substring(i, j+1)不是i,j。
DP实现
class Solution { public String longestPalindrome(String s) { if (s == null || s.length() == 0) { return ""; } boolean[][] dp = new boolean[s.length()][s.length()]; int ll = Integer.MIN_VALUE; int[] index = new int[2]; // the problem is caused when i and j are too close and i + 1 may cross with j - 1, but if they are close enough we can // just say by ourself. i==j, true, i + 1 == j, true, i + 2 == j, true // dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]; for (int i = s.length() - 1; i >= 0; i--) { for (int j = i; j < s.length(); j++) { dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]); if(dp[i][j] && j - i > ll) { ll = j - i; index[0] = i; index[1] = j; } } } return s.substring(index[0], index[1] + 1); } }
以上是关于leetcode5- Longest Palindromic Substring- medium的主要内容,如果未能解决你的问题,请参考以下文章
leetcode5. Longest Palindromic Substring
leetcode5- Longest Palindromic Substring- medium
LeetCode5. Longest Palindromic Substring 最大回文子串