[Day10]5. Longest Palindromic Substring

DESCRIPTION:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"Output: "bab"Note: "aba" is also a valid answer.
Example:
Input: "cbbd"Output: "bb"

ANALYSIS:

When I first saw this problem, some wrong ideas up to me. So, I asked SLF for some hints.
Then, I followed his thought and code for almost one hour and finally AC.

  1. Loop 'i' is the index of the middle of palindromic substring, and expand to left and right one by one at the same time
  2. One point should be pay attention to is that, the middle index of palindromic substring can be .5. For example, 'abba', its middle index is 1.5.
  3. I am disappointed in my speed in solve the index range of 'l' and 'r'. It takes me a lot of time to implement the code without some bugs like indexOutOfBoundException. Maybe it reminds me to practice more.

SOLUTION:

public static String longestPalindrome(String s) {
    String longestString="";
    for(double i=0.5;i<s.length()-1;i=i+1){
        double l=i-0.5;
        double r=i+0.5;
        while(l>=0&&r<s.length()&&s.charAt((int) l)==s.charAt((int) r)){
            l--;r++;
        }
        l++;r--;
        String string=s.substring((int)l,(int)r+1);
        if(string.length()>longestString.length())
            longestString=string;
    }
    for(int i=0;i<s.length();i++){
        int l=i;
        int r=i;
        while (l>=0&&r<s.length()&&s.charAt(l)==s.charAt(r)) {
            l--;r++;
        }
        l++;r--;
        String string=s.substring(l,r+1);
        if(string.length()>longestString.length())
            longestString=string;
    }
    return longestString;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,105評論 0 23
  • 由于工作是對日漢語教學,所以每天都能碰到各種各樣的日本人,或性格古怪,或溫柔隨和,或開朗有趣。普通的教學工...
    愛折騰的角落閱讀 587評論 0 1
  • 6當我知道回到家中,喚出阿爸二字沒人應(yīng)的時候,到現(xiàn)在已有半年之久?;谢秀便钡?,覺得想起爸爸的日子越來越少,一如既往...
    袖子_閱讀 430評論 7 0
  • 孤獨,是什么? 是清晨早起時,無方向的迷茫, 是人來人往的街頭上,越走越快的步伐, 為的是甩掉這身后的無盡繁華與熱...
    吃飽就睡唄閱讀 296評論 0 1

友情鏈接更多精彩內(nèi)容