码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode -- Day 54

时间:2015-08-26 01:31:55      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

palindrome

Question 1

Longest Palindromic Substring

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.
What‘s very smart here is start from a character, and get its i-1 and i+1 for compare.
 1     public String longestPalindrome(String s) {
 2         if (s == null || s.length() <=1)
 3             return s;
 4         
 5         int start = 0;
 6         int longest = 0;
 7         for (int i = 0; i < s.length();){
 8             int p1 = i;
 9             int p2 = i;
10             while(p2<s.length()-1 && s.charAt(p2) == s.charAt(p2+1)){
11                 p2 ++;
12             }
13             i = p2 + 1;
14             while(p1>0 && p2<s.length()-1 && s.charAt(p1-1) == s.charAt(p2+1)){
15                p1--;
16                p2++;
17             }
18             int len = p2 - p1 + 1;
19             if (len > longest){
20                 start = p1;
21                 longest = len;
22             }
23         }
24         return s.substring(start, start + longest);
25     }

 

Leetcode -- Day 54

标签:

原文地址:http://www.cnblogs.com/timoBlog/p/4759093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!