What is the central diffusion law?
The central diffusion method, as the name implies, is to take a certain position as the center and spread around until the conditions are met or the boundary is reached.
Leetcode 5. Longest palindrome substring
Title Description: given a string s, find the longest palindrome substring in S. You can assume that the maximum length of S is 1000.
Example 1: input: "babad", output: "bab", note: "aba" is also a valid answer.
Example 2: input: "cbbd", output: "bb"
Solution idea: traversing s, taking each char and two midpoint of char as the center, calculating the longest palindrome string with this point as the center;
For example: the string abcba has 5 (letters) + 4 (between two letters) = 9 center points; therefore, the string with length n has 2N-1 center points. Our goal is to count the longest palindrome strings S1, S2,..., s2n-1 centered on these 2N-1 points, and pick out the longest palindrome strings globally. Retain the maximum length palindrome string index, which is recorded as left and right; return the substring with left and right as the boundary after traversal
public class Solution { public static void main(String[] args) { Solution solution = new Solution(); String s1 = "babad"; System.out.println(solution.longestPalindrome(s1)); String s2 = "cbbd"; System.out.println(solution.longestPalindrome(s2)); String s4 = ""; System.out.println(solution.longestPalindrome(s4)); String s3 = null; System.out.println(solution.longestPalindrome(s3)); } public String longestPalindrome(String s) { if(null == s) { return null; } char[] charArray = s.toCharArray(); int length = charArray.length; int left = 0, right = 0, longestLength = 0; String longestPalindromeStr = ""; for(int i=0; i<length; i++) {//Spread around a single character, there are n Center ( n Is the length of the input string) left = i; right = i; while(left >= 0 && right < length && charArray[left] == charArray[right]) { left--; right++;//cabad } if(right - left - 1 > longestLength) { longestLength = right - left - 1; longestPalindromeStr = s.substring(left + 1, right); } } for(int i=0; i<length-1; i++) {//Spread with two characters as the center, then n-1 Center ( n Is the length of the input string) left = i; right = i+1; while(left >= 0 && right < length && charArray[left] == charArray[right]) { left--; right++; } if(right - left - 1 > longestLength) { longestLength = right - left - 1; longestPalindromeStr = s.substring(left + 1, right); } } return longestPalindromeStr; } }