首页 > 代码库 > [LeetCode]5 Longest Palindromic Substring
[LeetCode]5 Longest Palindromic Substring
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。