Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.
Problem solving idea One:
Brute Force enumeration
Total n^2 (starting from subscript zero), one for loop for each check, equals 3 for loop, Time complexity O (n^3)
Two ways to solve problems:
Dynamic planning
Set a table table[][], where table[i][j] means substring (i,j+1) is not palindromic, the time complexity is O (n^2) space complexity is also O (n^2).
The Java code is as follows:
static public String Longestpalindrome (string s) {if (s.length () ==1) return s; Int[][] table=new int[s.length ()][s.length ()]; int beginindex = 0,endindex = 0; Initializes the first, second slash for (int i=0;i<s.length (); i++) { table[i][i]=1; if (I==s.length ()-1) break; if (S.charat (i) ==s.charat (i+1)) { table[i][i+1]=1; beginindex=i; endindex=i+1; } } Assign the K slash value for (int k=2;k<s.length (), k++) {for (int i=0;i<s.length ()-k;i++) { if (table[i+1][i+ K-1]==1&&s.charat (i) ==s.charat (i+k)) { table[i][i+k]=1; beginindex=i; Endindex=i+k ; }}} PrintTable (table); Return s.substring (beginindex,endindex+1); } public static void PrintTable (Int. table[][]) {for (int. i=0;i<table.length;i++) {for (int j=0;j<table[i ].length;j++) { System.out.print (table[i][j]+ ""); } System.out.println ("");} }
Submit the results, Timeexceed. Proving that the time complexity is O (n^2) is not submitted for adoption.
Three ways to solve problems:
The center method, which is the center of each character in S and the repeating double character, is traversed. The time complexity is O (n^2), on Leetcode unexpectedly accepted!
The Java code is as follows:
static public String Longestpalindrome (string s) {if (s.length () = = 1) return s; string longest = s.substring (0, 1); for (int i = 0; i < s.length (); i++) {//Check single character center string tmp = Helper (s, I, I); if (TMP. Length () > Longest.length ()) longest = tmp;//Check multi-character Center tmp = Helper (s, I, i + 1); if (Tmp.length () > Longest.length ()) L Ongest = tmp;} return longest;} public static string helper (string s, int begin, int end) {while (Begin >= 0 && end <= s.length ()-1 && Amp S.charat (BEGIN) = = S.charat (end)) {begin--;end++;} return s.substring (begin + 1, end);}
Four ways to solve problems:
Manacher ' s algorithm
Java for Leetcode 005 longest palindromic Substring