LeetCode ---Longest Palindromic Substring
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode ---Longest Palindromic Substring相关的知识,希望对你有一定的参考价值。
1 public String longestPalindrome(String s) { 2 char[] ch = s.toCharArray(); 3 int longestLength = 0; 4 int[] longestIndex = {0, 0}; 5 for(int i = 0; i < ch.length; i++) { 6 int k = 0; 7 while((i + 1) > k && (i + k) <ch.length && ch[i - k] == ch[i + k]) { 8 if((2 * k + 1) > longestLength) { 9 longestLength = 2 * k + 1; 10 longestIndex[0] = i - k; 11 longestIndex[1] = i + k; 12 } 13 k++; 14 } 15 k = 0; 16 while(i + 1 > k && (i + k + 1) < ch.length && ch[i - k] == ch[i + k + 1]) { 17 if((2 * k + 2) > longestLength) { 18 longestLength = 2 * k + 2; 19 longestIndex[0] = i - k; 20 longestIndex[1] = i + k + 1; 21 } 22 k++; 23 } 24 } 25 return new String(ch, longestIndex[0], longestLength); 26 }
以上是关于LeetCode ---Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode409. Longest Palindrome
[Leetcode]Longest Palindromic Substring
leetcode longest consecutive sequence