leetcode 214: Shortest Palindrome
来源:互联网 发布:java基础入门培训学校 编辑:程序博客网 时间:2024/04/30 07:18
Shortest Palindrome
Total Accepted: 172 Total Submissions: 1344Given 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"
.
从某个char开始向两边扩展(左右两边的字符相等), 如果能一直扩展到字符串的头部, 则将末尾余下的reverse,再加到原字符串的头部,即可.
tips: 1. 中轴字符选从中间开始,这样找到的即为最短的. 2. 中轴字符可能为一个, 也可能为两个.
[CODE]
public class Solution { public String shortestPalindrome(String s) { if(s.length()<=1 ) return s; int center = (s.length()-1)/2; String res=""; for(int i=center; i>=0; i--) { if(s.charAt(i) == s.charAt(i+1)) { if( (res = check1(s, i, i+1)) !=null) return res; } if( (res = check1(s, i, i)) !=null) return res; } return res; } //aabaac private String check1(String s, int l, int r) { int i=1; for(; l-i>=0 && r+i<s.length(); i++) { if(s.charAt(l-i) != s.charAt(r+i) ) break; } if(l-i>=0) return null; StringBuilder sb = new StringBuilder(s.substring(r+i)); sb.reverse(); return sb+s; }}
1 0
- leetcode 214: Shortest Palindrome
- LeetCode #214 Shortest Palindrome
- leetcode 214: Shortest Palindrome
- [LeetCode 214] Shortest Palindrome
- LeetCode 214: Shortest Palindrome
- [leetcode-214]Shortest Palindrome(java)
- LeetCode 214 Shortest Palindrome (KMP next数组)
- leetcode - Shortest Palindrome
- LeetCode Shortest Palindrome
- 【回文】leetcode - Shortest Palindrome
- Shortest Palindrome Leetcode Java
- Shortest Palindrome leetcode-java
- [LeetCode] Shortest Palindrome I
- LeetCode - Shortest Palindrome (KMP)
- [leetcode] 214.Shortest Palindrome
- Shortest Palindrome -- leetcode
- LeetCode 214. Shortest Palindrome
- leetcode:Shortest Palindrome
- 没有错和对是两个概念
- 美国J1签证相关
- LeetCode 题解(91): Shortest Palindrome
- contest: Codeforces Round #300, problem: (B) Quasi Binary
- 无线应用安全剖析-sanr
- leetcode 214: Shortest Palindrome
- Netty+Spring
- TCHAR char
- CentOS查看CPU信息(CPU型号 CPU的个数 CPU是几核)命令
- 黑马程序员——java基础—000
- unicode 中 CW2A CA2W两个宏的含义
- NSLog 和 printf区别
- 从三字经看古代幼儿教育
- strcpy_s与strcpy的比较