Guest User

Palindromes

a guest
Oct 29th, 2014
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. /**
  2.  * Created by Foxes on 10/29/2014.
  3.  *
  4.  * For Anoni :3
  5.  */
  6.  
  7. import java.util.Scanner;
  8. public class Palindromes {
  9.     public static final String allowed = "abcdefghijklmnopqrstuvwxyz1234567890";
  10.     public static void main(String[] args) {
  11.         String original = "", smashed = "";
  12.         boolean bAskForText = (args.length == 0);
  13.         for (int word = 0; word < args.length; ++word) {
  14.             if (word == 0) original = args[0];
  15.             else {
  16.                 original = original + " " + args[word];
  17.             }
  18.         }
  19.         Scanner in = new Scanner(System. in );
  20.  
  21.         for (;;) {
  22.             if (bAskForText) {
  23.                 System.out.print("\n\nEnter text to check: ");
  24.                 original = in .nextLine();
  25.             } else bAskForText = true;
  26.  
  27.             smashed = original.toLowerCase();
  28.             if (smashed.contentEquals("quit")) System.exit(0);
  29.  
  30.             int palinSz = 1;
  31.             String found = "";
  32.  
  33.             for (int start = 0;
  34.             (start + palinSz) < smashed.length(); ++start) {
  35.                 for (int last = (start + palinSz); last < smashed.length(); ++last) {
  36.                     String testStr = smashed.substring(start, last + 1);
  37.                     if (testStr.length() > 1 && isPalin(testStr)) {
  38.                         found = testStr;
  39.                         palinSz = found.length();
  40.                     }
  41.                 }
  42.             }
  43.  
  44.             if (found.length() > 0) {
  45.                 System.out.println(" largest found: " + found);
  46.             } else {
  47.                 System.out.println(" no palindromes found.");
  48.             }
  49.         }
  50.     }
  51.  
  52.     private static boolean isPalin(String str) {
  53.         for (int i = 0; i < (str.length() / 2); ++i) {
  54.             int j = str.length() - (i + 1);
  55.             if (str.charAt(i) != str.charAt(j)) {
  56.                 dbg("  -:" + str);
  57.                 return false;
  58.             }
  59.             if (!allowed.contains(Character.toString(str.charAt(i)))) {
  60.                 dbg("  -:" + str);
  61.                 return false;
  62.             }
  63.         }
  64.         dbg(" **:" + str);
  65.         return true;
  66.     }
  67.  
  68.     private static void dbg(String s) {
  69.         boolean display = false;
  70.         if (display) {
  71.             System.out.println(s);
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment