方法应该接受一个单词,递归地通过字符串并找到与字母表两端相同距离的字母并删除它们。如果删除匹配,则不能再次使用这些字母。如果删除了每个字母,那么它就是匹配。
for (int i = 1; i < word.length()-1; i++)
{
if (word.charAt(0) + word.charAt(i) == 155)
{
StringBuilder sb = new StringBuilder(word);
sb.deleteCharAt(0);
sb.deleteCharAt(i);
String strNew = sb.toString();
System.out.println(strNew);
return isAlphaOpp(strNew);
}
}
return false;
}
答案 0 :(得分:1)
我稍微修改了你的方法,看看它。你需要与155进行比较,如果你的字符串是全部大写字母,如果你需要的所有小写字母都与219比较。正如@Raghu建议的那样,这不需要递归(这会让事情变得复杂),但我假设你想尝试这个递归。
public static boolean isAlphaOpp (String word)
{
//if word has odd number of characters, it cannot be an alpha opp
if (word.length() % 2 != 0)
{
return false;
}
//if string makes it to 0, then word must be an alpha opp
if (word.length() == 0)
{
return true;
}
/*if (word.charAt(0) + word.charAt(word.length()-1) == 155)
{
System.out.println(word.substring(1, word.length()-1));
return isAlphaOpp(word.substring(1, word.length()-1));
}
*/
//Should go thru each letter and compare the values with char(0). If char(0) + //char(i) == 155 (a match) then it should remove them and call the method again.
int length = word.length()-1;
int start = 0;
String newStr = null;
while(start < length) {
if(word.charAt(start) + word.charAt(length) == 219) {
StringBuilder sb = new StringBuilder(word);
sb.deleteCharAt(length);
sb.deleteCharAt(start);
newStr = sb.toString();
System.out.println(newStr);
start++;
length--;
break;
} else {
start++;
}
}
if(newStr != null) {
return isAlphaOpp(newStr);
}
return false;
}