Shortest Palindrome

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".

分析:

就是找出从原字符串中从第一个字符开始能够组成的最长palindome. 然后把原字符串中后面部分reverse后放在前面,这样整个字符串就是palindrome, 并且长度最小。

 1 public class Solution {
 2     public String shortestPalindrome(String s) {
 3         if (s == null || s.length() <= 1)
 4             return s;
 5         int size = 0;
 6         for (int i = 0; i <= (s.length() - 1) / 2; i++) {
 7             size = Math.max(size, maxSize(s, i, i));
 8             size = Math.max(size, maxSize(s, i, i + 1));
 9         }
10         String str = s.substring(size);
11         StringBuilder sb = new StringBuilder(str);
12         sb.reverse();
13         return sb.toString() + s;
14     }
15 
16     private int maxSize(String s, int left, int right) {
17         while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
18             left--;
19             right++;
20         }
21         if (left == -1) {
22             return right - left - 1;
23         }
24         return 0;
25     }
26 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5739840.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值