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

5. Longest Palindromic Substring

时间:2019-08-22 23:56:36      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:out   void   long   input   put   ansi   ring   hat   span   

Given a string s, find the longest palindromic substring in s. You may 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"
class Solution {
      private String res = "";//res全局变量
      public String longestPalindrome(String s) {
        if (s.length() <= 1) return s;
        for (int i = 0; i < s.length(); i++){
        midExpansion(s, i, i);  //for普通(aba)
        midExpansion(s, i , i + 1);   //for至少连续两个(aa)
        
        } 
           return res;
    }
        public void midExpansion(String s, int left, int right){
            while (right < s.length() && left >= 0  && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
            }
         if (right - left > res.length()){
             res = s.substring(left+1, right);  //比之前的长就更新,最后一次更新完left比预期小1
         }
            
        }
}

 

5. Longest Palindromic Substring

标签:out   void   long   input   put   ansi   ring   hat   span   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11397396.html

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