palindromic java_Longest Palindromic Substring leetcode java
題目:
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.
題解:
第一種方法就是挨個檢查,維護全局最長,時間復雜度為O(n3),會TLE。
代碼如下:
1?public?String?longestPalindrome(String?s)?{
2
3?????int?maxPalinLength?=?0;
4?????String?longestPalindrome?=?null;
5?????int?length?=?s.length();
6
7?????//check?all?possible?sub?strings8?????for?(int?i?=?0;?i?
9?????????for?(int?j?=?i?+?1;?j?
10?????????????int?len?=?j?-?i;
11?????????????String?curr?=?s.substring(i,?j?+?1);
12?????????????if?(isPalindrome(curr))?{
13?????????????????if?(len?>?maxPalinLength)?{
14?????????????????????longestPalindrome?=?curr;
15?????????????????????maxPalinLength?=?len;
16?????????????????}
17?????????????}
18?????????}
19?????}
20
21?????return?longestPalindrome;
22?}
23
24?public?boolean?isPalindrome(String?s)?{
25
26?????for?(int?i?=?0;?i?
27?????????if?(s.charAt(i)?!=?s.charAt(s.length()?-?1?-?i))?{
28?????????????return?false;
29?????????}
30?????}
31
32?????return?true;
33?}
第二種方法“是對于每個子串的中心(可以是一個字符,或者是兩個字符的間隙,比如串abc,中心可以是a,b,c,或者是ab的間隙,bc的間隙,例如aba是回文,abba也是回文,這兩種情況要分情況考慮)往兩邊同時進
行掃描,直到不是回文串為止。假設字符串的長度為n,那么中心的個數為2*n-1(字符作為中心有n個,間隙有n-1個)。對于每個中心往兩邊掃描的復雜
度為O(n),所以時間復雜度為O((2*n-1)*n)=O(n^2),空間復雜度為O(1)?!币訡ode ganker(http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html)
代碼如下:
1?????public?String?longestPalindrome(String?s)?{
2?????????if?(s.isEmpty()||s==null||s.length()?==?1)
3?????????????return?s;
4
5?????????String?longest?=?s.substring(0,?1);
6?????????for?(int?i?=?0;?i?
7?????????????//get?longest?palindrome?with?center?of?i8?????????????String?tmp?=?helper(s,?i,?i);
9
10?????????????if?(tmp.length()?>?longest.length())
11?????????????????longest?=?tmp;
12
13?????????????//get?longest?palindrome?with?center?of?i,?i+114?????????????tmp?=?helper(s,?i,?i?+?1);
15?????????????if?(tmp.length()?>?longest.length())
16?????????????????longest?=?tmp;
17?????????}
18
19?????????return?longest;
20?????}
21
22?????//Given?a?center,?either?one?letter?or?two?letter,23?//Find?longest?palindrome24?????public?String?helper(String?s,?int?begin,?int?end)?{
25?????????while?(begin?>=?0?&&?end?<=?s.length()?-?1?&&?s.charAt(begin)?==?s.charAt(end))?{
26?????????????begin--;
27?????????????end++;
28?????????}
29?????????return?s.substring(begin?+?1,?end);
30?????}
Reference:
http://www.programcreek.com/2013/12/leetcode-solution-of-longest-palindromic-substring-java/
http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html
總結
以上是生活随笔為你收集整理的palindromic java_Longest Palindromic Substring leetcode java的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机中有哪些视频后缀名
- 下一篇: java 继承和内部类_Java自学-接