天题系列: Shortest Palindrome
2015-06-18 03:33
337 查看
今天完整刷完leetcode除了自己看不懂follow不下来的 199道题。。。纪念一下
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given
Given
不想用kmp那种怪东东
完全抄自leetcode讨论http://www.programcreek.com/2014/06/leetcode-shortest-palindrome-java/
Analysis
We can solve this problem by using one of the methods which is used to solve the longest palindrome substring problem.
Specifically, we can start from the center and scan two sides. If read the left boundary, then the shortest palindrome is identified.
Java Solution
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given
"aacecaaa", return
"aaacecaaa".
Given
"abcd", return
"dcbabcd".
不想用kmp那种怪东东
完全抄自leetcode讨论http://www.programcreek.com/2014/06/leetcode-shortest-palindrome-java/
Analysis
We can solve this problem by using one of the methods which is used to solve the longest palindrome substring problem.
Specifically, we can start from the center and scan two sides. If read the left boundary, then the shortest palindrome is identified.
Java Solution
public String shortestPalindrome(String s) { if (s == null || s.length() <= 1) return s; String result = null; int len = s.length(); int mid = len / 2; for (int i = mid; i >= 1; i--) { if (s.charAt(i) == s.charAt(i - 1)) { if ((result = scanFromCenter(s, i - 1, i)) != null) return result; } else { if ((result = scanFromCenter(s, i - 1, i - 1)) != null) return result; } } return result; } private String scanFromCenter(String s, int l, int r) { int i = 1; //scan from center to both sides for (; l - i >= 0; i++) { if (s.charAt(l - i) != s.charAt(r + i)) break; } //if not end at the beginning of s, return null if (l - i >= 0) return null; StringBuilder sb = new StringBuilder(s.substring(r + i)); sb.reverse(); return sb.append(s).toString(); } |
相关文章推荐
- 探秘空值位图掩码(NULL bitmap mask)
- “四则运算解剖” 报告
- UML图的一些自我理解
- UML图的一些自我理解
- HashMap 专题
- 黑马程序员_反射2
- 【Android 动画】View Animation详解(一)
- 黑马程序员_IO
- eclipse导入JavaEE库
- Amazon AWS S3 部署静态网站 + 绑定顶级域名 + DNSPod
- BZOJ3211 花神游历各国(树状数组+并查集)
- 【C++探索之旅】开宗明义+第一部分第一课:什么是C++?
- Basic Calculator
- 最后一次阅读——13-17章
- Amazon AWS S3 部署静态网站 + 绑定顶级域名 + DNSPod
- 【C++探索之旅】开宗明义+第一部分第一课:什么是C++?
- LeetCode - Longest Valid Parentheses
- Prime Permutation
- 字符流,字节流,缓冲
- Linux Shell Bash 精彩脚本示例