Longest Palindromic Substring
来源:互联网 发布:linux finger 命令 编辑:程序博客网 时间:2024/06/05 23:23
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.
Given the string = "abcdzdcab"
, return "cdzdc"
.
O(n2) time is acceptable. Can you do it in O(n) time.
O(n^2): for example: “a”, transfer “a”to “#a#”, “ab”, transfer “ab” to “#a#b#”. This step transfer all string to oddlength. Then traverse all string, every time set a count equals one. This countmeans the length you extend to left and right side. while (i - count >= 0&& i + count <= len + 1 && (getChar(s, i - count) ==getChar(s, i + count))), you should continue extend substring. For getChar function,if (i%2 == 0), return ‘#’, else return s(i/2). Back to the main function, comparemax with count and update substring. If you cannot sure the parameter in codelike i, i + 1, (i+count)/2, you can use “a” as example to determine it. Code as following:
public class Solution { /** * @param s input string * @return the longest palindromic substring */ public String longestPalindrome(String s) { // Write your code here int max = 0, len = s.length() * 2 - 1; String res = ""; for (int i = 1; i <= len; i ++) { int count = 1; while (i - count >= 0 && i + count <= len + 1 && (getChar(s, i - count) == getChar(s, i + count))) { count ++; } count --; if (max < count) { max = count; res = s.substring((i - count) / 2, (i + count) / 2); } } return res; } private char getChar(String s, int i) { if (i % 2 == 0) { return '#'; } else { return s.charAt(i / 2); } }}
O(n): Manacher's Algorithm: …….
- LeetCode: Longest Palindromic Substring
- LeetCode Longest Palindromic Substring
- LeetCode: Longest Palindromic Substring
- [Leetcode] Longest Palindromic Substring
- Longest Palindromic substring
- [LeetCode] Longest Palindromic Substring
- LeetCode5:Longest Palindromic Substring
- Leetcode : Longest Palindromic Substring
- Longest Palindromic Substring
- Longest Palindromic Substring
- [LeetCode]Longest Palindromic Substring
- leetcode Longest Palindromic Substring
- Longest Palindromic Substring
- LeetCode-Longest Palindromic Substring
- Longest Palindromic Substring
- Longest Palindromic Substring
- [LeetCode] Longest Palindromic Substring
- Longest Palindromic Substring leetcode
- h1,p
- Python学习笔记-数字&字符串
- 【JAVA集合详解】LinkedList
- xshell上传文件到Linux服务器以及下载
- AtCoder Regular Contest 077-C
- Longest Palindromic Substring
- hadoop初级遇到的问题
- SPI、I2C、UART、I2S、GPIO、SDIO、CAN简述
- Lua中的常用函数库汇总
- 【Java】一台服务器配置多个Tomcat
- xshell上传文件到Linux服务器以及下载
- js解析与读取JSON数据
- POJ 1023--The Fun Number System
- JavaScript高级程序设计笔记-8.1