java Java中的Palindrome算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Java中的Palindrome算法相关的知识,希望对你有一定的参考价值。

// Lab2.java Starter File

import java.io.*; // BufferedReader
import java.util.*; // Scanner

public class Lab2
{
  public static void main (String args[]) throws Exception // i.e. the input file you put on cmd line is not in directory
  {
    // ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED INPUT FILE NAME ON THE COMMAND LINE
    if (args.length < 1 )
    {
      System.out.println("\nusage: C:\\> java Lab2 <input filename>\n\n"); // i.e. C:\> java Lab2 input.txt
      System.exit(0);
    }
    BufferedReader infile = new BufferedReader (new FileReader( args[0] )); // we read our text file line by line
    int lineNum=0;
    while( infile.ready() )
    {
      String line = toAlphaLowerCase(infile.readLine());
      if ( isPalindrome( line ) )
      System.out.format("<%s> IS palindrome.\n",line);
      else
      System.out.format("<%s> NOT palindrome.\n",line);
    }
  } // END MAIN
  
  // ******* MODIFY NOTHING ABOVE  THIS   LINE YOU FILL IN THE METHODS BELOW *******
  // RETURNS A STRING WITH ALL NON ALPHABETIC CHARS REMOVED. ALL REMAINING ARE ALPHAS CONVERTED TO LOWER CASE
  // "Madam I'm Adam" returns "madamimadam" which is now ready for a simple palindromic test
  // To test whether a char is alpha i.e. letter of the alphabet
  // read this ==> https://docs.oracle.com/javase/tutorial/i18n/text/charintro.html
  static String toAlphaLowerCase( String s )
  {
    String clean = "";
    for (int i = 0; i < s.length(); i++) {
      
      if (Character.isLetter(s.charAt(i)) == true)
      clean += Character.toLowerCase(s.charAt(i));
    }
    return clean; // (just to make it compile) YOU CHANGE AS NEEDED
  }
  // RETURNs true if and only if the string passed in is a palindrome
  static boolean isPalindrome( String s )
  {
    if (s.equals("") || s == null) {
      return true;
    }
    
    
    for (int i = 0; i < s.length() / 2; i++) {
      if (s.charAt(s.length() - 1 - i) != s.charAt(i)) {
        return false;
      }
    }
    return true; // (just to make it compile) YOU CHANGE AS NEEDED
  }
} // END LAB2 CLASS

以上是关于java Java中的Palindrome算法的主要内容,如果未能解决你的问题,请参考以下文章

java 234. Palindrome Linked List(#)。java

java 234. Palindrome Linked List(#)。java

java 234. Palindrome Linked List(#)。java

java 234. Palindrome Linked List(#)。java

java 267. Palindrome Permutation II.java

java 267. Palindrome Permutation II.java