标签:
1. Title
Longest Palindromic Substring
2. Http address
https://leetcode.com/problems/longest-palindromic-substring/
3. The question
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
4. My code (AC)
1 // Accepted 2 public static String longestPalindrome(String s) { 3 4 if ( s == null) 5 return s; 6 int len = s.length(); 7 if ( len <= 1) 8 return s; 9 boolean isPalindrome[][] = new boolean[len][len]; 10 int start = 0; 11 int maxLen = 0; 12 for(int i = 0 ; i < len; i++) 13 { 14 isPalindrome[i][i] = true; 15 start = i; 16 maxLen = 1; 17 } 18 19 for(int i = 0 ; i < len - 1; i++) 20 { 21 if ( s.charAt(i) == s.charAt(i+1)){ 22 isPalindrome[i][i+1] = true; 23 start = i; 24 maxLen = 2; 25 } 26 } 27 28 for( int i = len - 3; i >=0 ; i--) 29 { 30 for( int j = i + 2; j < len; j++) 31 { 32 if( s.charAt(i) == s.charAt(j) && isPalindrome[i+1][j-1]) 33 { 34 isPalindrome[i][j] = true; 35 if ( maxLen < (j - i + 1)) 36 { 37 start = i; 38 maxLen = j - i + 1; 39 } 40 } 41 } 42 } 43 for( int i = 0 ; i < len ; i++) 44 { 45 System.out.println(); 46 for( int j = 0 ; j < len ; j++) 47 { 48 System.out.print(" " + isPalindrome[i][j]); 49 } 50 System.out.println(); 51 } 52 System.out.println(start); 53 System.out.println(maxLen); 54 return s.substring(start, start + maxLen); 55 }
标签:
原文地址:http://www.cnblogs.com/ordili/p/4970034.html