回文使用 JAVA 中的字符串

Palindrome using string in JAVA

我正在尝试创建一个名为 "palindrome" 的方法,它接收一个字符串和 returns 一个布尔值,如果该字符串是回文,则为 true,否则为 false。如果一个词正向和反向读相同,则它是回文。比如单词level就是回文

例如考虑通过删除所有空格和标点符号并将所有字母转换为小写形式获得的文本作为回文:

女士,我是亚当 ==> 女士女士

一个人,一个计划,一条运河:巴拿马 ==> amanaplanacanalpanama

我尝试处理我使用的代码 replaceAll(); 并将输出作为全部替换的最后一行。

public static String palindrome(String n){

      char[] input = n.toCharArray();

    //for(int i=0; i<input.length; i++){ //looping reversing using input as in length minus 1 from end to start and counting using increment
      n.toLowerCase();
      String noSpaces = n.replaceAll(" ", ""); //I used this to get string 
      String remove = noSpaces.replaceAll(",","");
      String remove2 = remove.replaceAll(".","");
      String remove3 = remove2.replaceAll(":","");
      String remove4 = remove3.replaceAll("!", "");
      System.out.print(remove4);    
      //return n;  
    //}
    return n;
    }

Compiler/Output:

Input: Madam, I'm Adam

Output:

输出什么也没显示?我究竟做错了什么?

Java 的 replaceAll() 的第一个参数是正则表达式。 . 在正则表达式中匹配任何字符,所以 remove.replaceAll(".", "") 实际上给你一个空字符串。

转义句号,你应该会再次返回一个字符串。

String remove2 = remove.replaceAll("\.","");

问题是点基本上匹配任意字符任意次数。所以如果你把 remove.replaceAll(".","") 所有的字符都替换掉了。您应该转义点以指定实际点。希望这有帮助。

n = n.toLowerCase();//you should assign the result to get lowercase characters
String noSpaces = n.replaceAll(" ", ""); //I used this to get string 
String remove = noSpaces.replaceAll(",","");
String remove2 = remove.replaceAll("\.","");
String remove3 = remove2.replaceAll(":","");
String remove4 = remove3.replaceAll("!", "");
String remove5 = remove2.replaceAll("\'","");//you should also escape apostrophe
System.out.print(remove5);

要删除所有特殊字符,只需使用 remove.replaceAll("\p{Punct}", "")

此外,您可以像这样链接 "removes" 来简化代码:

String output = n.toLowerCase().replaceAll(" ", "").replaceAll("\p{Punct}", "");
System.out.println(output);

现在,这本身并不是 return 回文,也不会对其进行检查。要检查回文,您必须创建一个方法,将指针放在字符串的首尾两端,并比较两个索引处的字符以查看它们是否匹配。您将分别递增和递减这些指针,直到:

  1. 字符不一样,或者
  2. 尾指针的值小于头指针。

例如:

boolean isPalindrome(String word) {
    int headPtr = 0;
    int tailPtr = word.length() -1 ;

    while (headPtr < tailPtr) {
        if (word.charAt(headPtr) != word.charAt(tailPtr))
            return false;
        headPtr++;
        tailPtr--;
    }
    return true;
}

您可以测试偶数和奇数字符串以确保中断条件正确。例如 otto、hannah、1234321,甚至您的长短语。完成的实施应如下所示:

public class PalindromeTest {

    static boolean isPalindrome(String word) {
      int headPtr = 0;
      int tailPtr = word.length() -1 ;

      while (headPtr < tailPtr) {
        if (word.charAt(headPtr) != word.charAt(tailPtr))
            return false;
        headPtr++;
        tailPtr--;
      }
      return true;
  }

  public static void main (String[] args) {

    String n = "A man, a plan, a canal: Panama";

    String output = n.toLowerCase().replaceAll(" ", "").replaceAll("\p{Punct}", "");
    System.out.println(n + " is palindrome? " + isPalindrome(output));
  }
}