标签:leetcode
https://oj.leetcode.com/problems/longest-palindromic-substring/
http://fisherlei.blogspot.com/2012/12/leetcode-longest-palindromic-substring.html
public class Solution { public String longestPalindrome(String s) { // Solution A: return longestPalindrome_Center(s); } /////////////////////////////////////// // Solution A: Center // // 遍历每一个字符,寻找以此字符为中心,最长的回文 // O(n ^ 2) public String longestPalindrome_Center(String s) { if (s == null || s.length() == 0 || s.length() == 1) return s; char[] chars = s.toCharArray(); int len = chars.length; int maxStart = -1; int maxLen = 0; for (int i = 0 ; i < len ; i ++) { // 寻找以i-1,i为中点偶数长度的回文 int low = i - 1; int high = i; while (low >= 0 && high < len && chars[low] == chars[high]) { low --; high ++; } low ++; high --; int curLen = high - low + 1; if (curLen > maxLen) { maxStart = low; maxLen = curLen; } // 寻找以i为中心的奇数长度的回文 low = i - 1; high = i + 1; while (low >= 0 && high < len && chars[low] == chars[high]) { low --; high ++; } low ++; high --; curLen = high - low + 1; if (curLen > maxLen) { maxStart = low; maxLen = curLen; } } return s.substring(maxStart, maxStart + maxLen); } /////////////////////////////////////// // Solution B: Brute Force // // O(n ^ 3) public String longestPalindrome_BruteForce(String s) { if (s == null || s.length() == 0 || s.length() == 1) return s; char[] chars = s.toCharArray(); int len = chars.length; for (int size = len ; size > 0 ; size --) { for (int offset = 0 ; offset < len - size + 1 ; offset ++) { if (isPalin(chars, offset, offset + size - 1)) { return s.substring(offset, offset + size); } } } return null; } // if chars[start] -> chars[end] is palin private boolean isPalin(char[] chars, int start, int end) { for (int i = 0 ; start + i < end - i ; i ++) { if (chars[start + i] != chars[end - i]) return false; } return true; } }
[LeetCode]5 Longest Palindromic Substring
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598396