Given a string, find out the maximum number of chunked palindrome, the normal palindrome is ABCCBA, chunked palindrome is defined as: For example, Volvo, can be the VO division, (VO) (l) (VO), Then it's a palindrome. Returns the maximum number of chunk to be implemented. For example, AAAAAA can be (AAA) (AAA), but the maximum chunk quantity should be (a) (a) (a) (a) (a) (a) to 6
This is a greedy problem, starting with the sides of the string, using I and J to record where the current scan is, using Prev_i and Prev_j to record the next character of the position of chunk I and J. Finally sweep to the middle to determine whether there is no extra chunk.
Time complexity O (n^2) with O (N) complexity in the inner layer string.equals
1 PackageChunkedpalindrome;2 3 Public classSolution {4 Public intcountchunk (String str) {5 if(str==NULL|| Str.length () ==0)return0;6 intsum = 0;7 intL=0, R=str.length ()-1;8 intPreL = L, Prer =R;9 while(L <r) {TenString left = str.substring (PreL, l+1); OneString right = Str.substring (R, prer+1); A if(Left.equals (right)) { -PreL = l+1; -Prer = R-1; theSum + = 2; - } -l++; -r--; + } - if(PreL <= prer) sum+=1; + returnsum; A } at - - /** - * @paramargs - */ - Public Static voidMain (string[] args) { in //TODO auto-generated Method Stub -Solution Sol =Newsolution (); to intres = Sol.countchunk ("aaaaaa"); + System.out.println (res); - } the *}
G-Face via prepare:chucked palindrome