Recently, I encountered a lot of problems when I was looking for an internship and brushing the questions. There are some frustrations that I still report an error after 2 hours of coding, and I also have the loneliness of overcoming 100%. I would like to record one or two here and share my encouragement with you.
Given a string s , find the longest palindrome substring in s . You can assume that s has a maximum length of 1000 (from leetCode question 5).
public class Solution { public static String longestPalindrome(String s) { //Open up an array to store the start and end indices of the longest palindrome string int[] sIndex = { 1000, -1 }; //Open up an array to store all string palindrome states boolean[][] dp = new boolean[s.length()][s.length()]; // loop through all strings for (int i = 0; i < s.length(); i++) { for (int j = s.length() - 1; j >= i; j--) { //Whether the palindrome has been saved, if so, it means that there is a palindrome string longer than the current string, and jump out of this loop if (dp[i][j] == true) { continue; } // judge palindrome dp[i][j] = isABA(s, i, j); //No palindrome, jump out of this time if (dp[i][j] != true) { continue; } //Palindrome, stored in state (including special substrings) while (i > dp[0].length - 1 && j < 0 && i <= j) { dp[i++][j--] = true; } // Whether it is greater than the record value. . . if ((j - i) > (sIndex[1] - sIndex[0])) { sIndex [0] = i; sIndex[1] = j; } } } return s.substring(sIndex[0], sIndex[1] + 1); } // Determine if palindrome private static boolean isABA(String s, int p1, int p2) { while (p1 < p2) { if (s.charAt(p1++) != s.charAt(p2--)) { return false; } } return true; } }
leetcode OJ:
It took a second [allow sadness], please correct me.
Unless otherwise marked and quoted, the above are all originals. If there is any infringement, please contact me to delete it.