LeeCode_回文字符串

Input: “abca”
Output: True
Explanation: You could delete the character ‘c’.

  • 题目描述:可以删除一个字符,判断是否能构成回文字符串。
/**
 * Input: "abca"
 * Output: True
 * Explanation: You could delete the character 'c'.
 * 题目描述:可以删除一个字符,判断是否能构成回文字符串。
 * @author 林博弈
 *
 */
public class Four_回文字符串 {
	public static void main(String[] args) {
		/*
		 * 测试用例:
		 * 功能测试:String a = "abcdcba";  String b = "abcdecba";
		 * 边界值:String c = "abcdcbbba"; String d = "";
		 * 非法输入:String e = null;
		 */
		String a = "abcdcba";
		String b = "abcdecba";
		validPalindrome(a);
		validPalindrome(b);
		
		
		String c = "abcdcbbba";
		String d = "";
		validPalindrome(c);
		validPalindrome(d);
		
		String e = null;
		validPalindrome(e);
	}
	public static boolean validPalindrome(String s) {
		char[] chars = s.toCharArray();
		int first = 0;
		int end = chars.length-1;
		int chance = 0;
		int change = -1; //-1为无需更改
		
		if(s.equals("")){
			System.out.println("It is empty.");
			return false;
		}
		
		while(first!=end&&chance<2){
			if(chars[first]==chars[end]){
				first++;
				end--;
			}else if(chars[first]!=chars[end]){
				chance++;
				if(chars[first+1]==chars[end]){
					change = first;
					first++;
					continue;
				}else if(chars[first]==chars[end-1]){
					change = end;
					end--;
					continue;
				}
			}
		}
		if(first==end&&chance==0){
			System.out.println("It is Palindrome.");
			return true;
		}else if(first==end&&chance==1){
			System.out.println("Explanation: You could delete the character '"+chars[change]+"'.");
			return true;
		}else{
			System.out.println("It isn't Palindrome.");
			return false;
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值