您的位置:首页 > 编程语言 > Java开发

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

2016-01-04 11:21 459 查看
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;
	 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: