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;
}
}
}