[LeetCode] 5. 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.

Example:
Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.```
######Example:

Input: "cbbd"

Output: "bb"```


</br>

Solution

The most straightforward way to implement this is to iterate all various substrings and individually check whether it is palindromic and outputs the longest one.

public class Solution {
    public String longestPalindrome(String s) {
        
        int i = 0, j = 0, k = 0, t = 0, max = 1;
        int n = s.length();
        boolean isPalindrome = false;
        String maxString = new String();
        
        Set<Character> set = new HashSet<>();
        
        for (i = 0;i < n;i++){
            for (j = i;j < n;j++){
                for (k = 0;k <= j-i;){
                    if (s.charAt(i+k) == s.charAt(j-k))
                        isPalindrome = true;
                    else{
                        isPalindrome = false;
                        break;
                    }
                    k++;
                }
                
                if (isPalindrome){
                    if (max <= j-i+1){
                        max = j-i+1;
                        maxString = s.substring(i,j+1);
                    }
                }
            }
        }
        return maxString;
    }
}

Clearly, this method may lead to Time Limit Exceeded.

Therefore a more efficient way is needed. Instead of inspecting every substring to check whether it is palindromic or not, we should try to build palindromic words from ground up. As abcdcba, the words are mirrored from the middle character. Then if s[i,j] is palindromic, we only have to check if the character in front of it and behind it is the same to determine whether s[i-1,j+1] is palindromic.

Hence, rather than iterating all substrings, we only have to check all the available middle spot. In a string of n characters, there is a total of 2n-1 middle spots.

The code is shown below.

public class Solution {
    public String longestPalindrome(String s) {
        
        int l = 0, r = 0, max = 0;
        
        for (int i = 0; i < s.length() ;i++){
            int len1 = substringBuilder(s,i,i);
            int len2 = substringBuilder(s,i,i+1);
            int len = Math.max(len1,len2);
            
            if(len > max){
                l = i - (len-1)/2;
                r = i + len/2 + 1;
                max = len;
            }
        }
        
        return s.substring(l, r);
    }
    
    public int substringBuilder(String s, int left, int right){
        
        int start = left, end = right;
        
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
            start --;
            end ++;
        }
        
        return end - start - 1;
    }
}

The trick in the solution is to focus on the output on the substringBuilder, because we compare two situation of middle points at s[i,i] and s[i,i+1], if the middle point is at the s[i,i+1], then the length of the palindromic substring is even, which means the least length is 0 or 2; then we should return end - start - 1 as the length of the substring instead of end - start.
</br>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末玫恳,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子湾宙,更是在濱河造成了極大的恐慌寸莫,老刑警劉巖坷檩,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件管引,死亡現(xiàn)場(chǎng)離奇詭異货抄,居然都是意外死亡漆改,警方通過(guò)查閱死者的電腦和手機(jī)沾瓦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)满着,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人贯莺,你說(shuō)我怎么就攤上這事风喇。” “怎么了缕探?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵魂莫,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我爹耗,道長(zhǎng)耙考,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任潭兽,我火速辦了婚禮倦始,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘山卦。我一直安慰自己鞋邑,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布账蓉。 她就那樣靜靜地躺著枚碗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪铸本。 梳的紋絲不亂的頭發(fā)上肮雨,一...
    開(kāi)封第一講書(shū)人閱讀 51,443評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音箱玷,去河邊找鬼怨规。 笑死,一個(gè)胖子當(dāng)著我的面吹牛汪茧,可吹牛的內(nèi)容都是我干的椅亚。 我是一名探鬼主播限番,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼舱污,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了弥虐?” 一聲冷哼從身側(cè)響起扩灯,我...
    開(kāi)封第一講書(shū)人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤媚赖,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后珠插,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體惧磺,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年捻撑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了磨隘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡顾患,死狀恐怖番捂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情江解,我是刑警寧澤设预,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站犁河,受9級(jí)特大地震影響鳖枕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜桨螺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一宾符、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧灭翔,春花似錦吸奴、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至狭园,卻和暖如春读处,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背唱矛。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工罚舱, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人绎谦。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓管闷,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親窃肠。 傳聞我的和親對(duì)象是個(gè)殘疾皇子包个,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,744評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,495評(píng)論 0 23
  • 戀愛(ài) 隨著長(zhǎng)大冤留,人們對(duì)戀愛(ài)的理解碧囊,看法树灶,和作為都會(huì)變。雖然有些人戀愛(ài)過(guò)后糯而,會(huì)有不想再戀愛(ài)的想法天通,但終究還是會(huì)戀愛(ài)。...
    Zhao_Z_C_閱讀 269評(píng)論 2 2
  • 記得參加趁早第二期早餐打卡的時(shí)候,就聽(tīng)組長(zhǎng)說(shuō):“第一期100天趁早換新計(jì)劃瓜贾,有20000萬(wàn)多人報(bào)名萝映,100天過(guò)后,...
    十七碎碎念閱讀 352評(píng)論 0 3
  • 你和謝曼的相識(shí),起源于一張你的愿望清單实束。 那個(gè)不曾謀面的女孩用一句話劃定了你們的牽絆奥秆。 她說(shuō):我們有很多相同的夢(mèng)想...
    狂暴的索理子閱讀 799評(píng)論 0 3