所以我最近上大学并且表现相当不错,这导致我加入了编程竞赛。
在一项任务中,我们被要求创建一个程序,要求用户输入一个字符串。之后,程序需要查看字符串是否为回文结构而忽略空格和特殊字符。
实施例: 马...... a.m:回文 没有....魔鬼......,.'....生活......在
即使在比赛结束后,我也尽力回答这个问题。我设法通过它并且有资格参加下一轮比赛,但这项任务让我在夜间做了噩梦lol
答案 0 :(得分:0)
我会像这个伪代码一样解决这个问题:
letters <== ""
characterEntered ( letters, c ) {
if (c is an uppercase letter) lowercase(c)
if (c is a letter) append c to letters
/* otherwise forget about it */
}
allCharactersEntered ( list ) {
backwards <== reverse(letters)
if (backwards equals letters) say "Palindrome"
else say "Nope"
}
答案 1 :(得分:0)
Java版:
public static void main(String[] args) {
palin();
}
public static void palin() {
String in = null;
// loop
while (true) {
// read input
in = readInput();
// check input
if ("q".equalsIgnoreCase(in)) {
// exit
break;
}
if (checkPalindrome(in)) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
private static boolean checkPalindrome(String in) {
String sanitizedIn = sanitize(in);
return sanitizedIn.equalsIgnoreCase(StringUtils.reverse(sanitizedIn));
}
private static String sanitize(String in) {
String result = null;
Pattern p = Pattern.compile("[^a-zA-Z0-9]+");
Matcher m = p.matcher(in);
result = m.replaceAll("");
System.out.println(in + "|>>>>>|" + result);
return result;
}
private static String readInput() {
try {
System.out.println("Enter text(q to Quit):");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
答案 2 :(得分:0)
这是更有效的解决方案
private boolean isPalindrome(String text) {
int index1 = 0;
int index2 = text.length() - 1;
char[] chars = text.toCharArray();
if (!Character.isLetter(chars[index1])) {
index1 = nextLetterIndex(chars, index1);
}
if (!Character.isLetter(chars[index2])) {
index2 = previousLetterIndex(chars, index2);
}
while (index2 >= index1) {
if (Character.toLowerCase(chars[index1]) != Character.toLowerCase(chars[index2])) {
return false;
}
index1 = nextLetterIndex(chars, index1);
index2 = previousLetterIndex(chars, index2);
}
return true;
}
int previousLetterIndex(char[] chars, int index) {
index--;
while (!Character.isLetter(chars[index])) {
index--;
}
return index;
}
int nextLetterIndex(char[] chars, int index) {
index++;
while (!Character.isLetter(chars[index])) {
index++;
}
return index;
}
答案 3 :(得分:0)
public boolean isPalindromeSpecialCharacters(String input)
{
if (input == null)
return false;
String stringWithoutSpecials = "";
char charArr[] = input.toCharArray();
for (char ch : charArr)
{
if (Character.isLetter(ch))
stringWithoutSpecials += ch;
}
if (stringWithoutSpecials.equals(this.reverseString(stringWithoutSpecials)))
return true;
return false;
}
public String reverseString(String text)
{
if (text == null || text.isEmpty())
return text;
return reverseString(text.substring(1)) + text.charAt(0);
}