[Java]LeetCode5 Longest Palindromic Substring

來源:互聯網
上載者:User

標籤:leetcode

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.

題意:求字元串中最長的迴文

感覺這題不難,可以這樣想,設定兩個指標,分別對應0,len-1。

比如從第一個字元開始,abababac,我們可以找a出現的位置,然後以第一個a與每個a作為一段。判斷每一段是否是迴文,因為是從後往前尋找的,所以第一個找到的肯定是這一次尋找中最長的迴文,然後一次第2個字元,第3個字元。這個想法在字串中的字元不一樣的時候比較好。但是如果字元中出現的例如aaaaaabcaaaaa這樣的話,就不佳了。在leetcode中一測試,果然TimeLimited。

第二個想法,算是逆推法,既然求的是迴文,迴文的字元是對稱的。我們可以先確定迴文的中心,迴文的中心,奇數的時候是一個,偶數的時候是兩個。分別向中心的兩邊進行匹配,判斷是否相等,從而計算迴文的長度。

代碼如下:

public static String longestPalindrome(String s) {       if(s.isEmpty()||s.length()==1)return s;       String longest=s.substring(0,1);       for(int i=0;i<s.length();i++)       {           //將i作為中心,擷取最長的字串           String tmp=isPalindrome(s,i,i);           if(tmp.length()>longest.length())longest=tmp;           //將i,i+1作為中心,獲得最長的字串            tmp=isPalindrome(s,i,i+1);           if(tmp.length()>longest.length())longest=tmp;       }       return longest;   }private static String isPalindrome(String s, int start, int end)    {        // TODO Auto-generated method stub        while(start>=0&&end<=s.length()-1&&s.charAt(start)==s.charAt(end))        {            start--;            end++;        }        return s.substring(start+1,end);    }


[Java]LeetCode5 Longest Palindromic Substring

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.