标签:leetcode java 算法 数据结构 substring
</pre><pre name="code" class="java">public class Solution { public String longestPalindrome(String s) { int down = 0,up = 0,count = 0; //分别记录扫字符串时的上下区间及字符串长度 int sl = s.length(); int maxl = 0; int subDown = 0, subUp = 0; //目标子字符串的上下区间 String subS = new String(""); if(sl==0) return ""; //1. 找出目标子字符串的中间位置及上下限 for(double i=0; i<=sl-1; i=i+0.5) { down = (int)Math.floor(i); up = (int)Math.ceil(i); if((i%1==0.5)&&sl!=0) //判断i所属情况(A或B) { count = 0; }else { count = 1; down--; up++; } //2. 以i为中心向两边扫描 while(!(down<0||up>sl-1)) { if(s.charAt(down)!=(s.charAt(up))) { break; //2.1. 当以i为中心对称的俩字符不相等则跳出扫描 }else{ //2.2. 当以i为中心对称的俩字符相等则继续分别向两边移动 count+=2; down--; up++; } } //3. 更新最长字符串 if(count>maxl) { maxl = count; subDown = down; subUp = up; } } //3.1 由于在扫描时,先移动后再判断,停止时其实前后都多移动了一个单位,这里进行一个单位的恢复 subDown++; subUp--; subS = s.substring(subDown,subUp+1); return subS;//返回对称子字符串 } }
扩展学习:该文章介绍了几种方法Java Longest Palindromic Substring(最长回文字符串)
LeetCode【5】. Longest Palindromic Substring --java实现
标签:leetcode java 算法 数据结构 substring
原文地址:http://blog.csdn.net/waycaiqi/article/details/46127733