蘑菇街2016招聘笔试(回文串)

题目描述


给定一个字符串,问是否能通过添加一个字母将其变为回文串。


输入描述:


一行一个由小写字母构成的字符串,字符串长度小于等于10。


输出描述:


输出答案(YES\NO).


输入例子:


coco


输出例子:


YES



思路通过将字符串反转后,与原字符串进行最长公共子串处理,得到lcs的值,则所需添加长度 = 字符串长度-lcs,判断是否小于等于1即可
public class Solution {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		String s = "coco";
		System.out.println(Solution.canBeHUIWEN(s) );
	}

	public static String canBeHUIWEN(String s) {
		String reverseS = reverse(s.toCharArray());
		int lcs = LCS(s, reverseS);
		int addNums = s.length() - lcs;
		if (addNums <= 1)
			return "yes";
		else
			return "no";
	}

	public static String reverse(char[] str) {
		int s = 0;
		int e = str.length - 1;
		while (s < e) {
			char temp = str[s];
			str[s] = str[e];
			str[e] = temp;
			++s;
			--e;
		}
		return new String(str);
	}

	public static int LCS(String s1, String s2) {
		int len1 = s1.length();
		int len2 = s2.length();
		String res = "";
		int[][] DP = new int[len1 + 1][len2 + 1];// 初始化一个比两个字符串长度+1的二维数组
		for (int i = 0; i <= len1; i++) {
			for (int j = 0; j <= len2; j++) {
				if (i == 0 || j == 0) {
					DP[i][j] = 0;// 从边界开始,当一个字符串为空的时候,肯定为0
				}
				// 如果xm=yn,则zk=xm=yn 有Zk−1是Xm−1与Yn−1的LCS;
				else if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
					DP[i][j] = 1 + DP[i - 1][j - 1];
				} else {
					// 如果xm≠yn,则Zk是Xm与Yn−1的LCS,或者是Xm−1与Yn的LCS。
					DP[i][j] = Math.max(DP[i - 1][j], DP[i][j - 1]);
				}
			}
		}
		// System.out.println(res);
		return DP[len1][len2];
		// return res;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值