leetcode 214:Shortest Palindrome 题目分析 与使用KMP算法的java实现

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

题目分析:

这个题目是在字符串前面加字符构成一个最短的回文字符串。我们分析题意,就是找到从第一个字母起始的最长的回文字符串,然后把剩下的倒置加到前面,就得到了最短的回文字符串。怎么找到以第一个字母为起始的最长的回文串,我们可以把s转置,然后找到匹配转置后的字符串从原始字符串第一个开始位置能够匹配的最大长度。这时候我们可以考虑到使用KMP算法,因为KMP算法就是从目标字符串的第一个字母开始匹配。我们可以这么做

S+“#”+S.reverse 然后使用KMP算法

具体代码如下:

public String shortestPalindrome(String s) {
		 String tmp=s+"#"+new StringBuilder(s).reverse().toString();
		 int[] table=getTable(tmp);
		 return new StringBuilder(s.substring(table[table.length-1])).reverse().toString()+s;
		 
	 }
	 //KMP算法
	 public int[] getTable(String s)
	 {
		 int len=s.length();
		 int[] table=new int[len];
		 char[] a=s.toCharArray();
		 //i是从1开始
		 for(int i=1,k=0;i<len;i++)
		 {
			 while(k>0&&a[i]!=a[k])
			 {
				 k=table[k-1];
			 }
			 if(a[i]==a[k])
				 k++;
			 table[i]=k;
		 }
		 return table;
	 }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值