Advertisement
josebaperu

Untitled

Jul 1st, 2015
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. import java.util.Set;
  2. import java.util.TreeSet;
  3.  
  4. public class Palindrome{
  5.  
  6.  static int loop =0;
  7.  
  8.    public static boolean checkPalindrome(String word){
  9.      
  10.      int length = word.length();
  11.      
  12.      if(length ==0 && loop ==0){
  13.        loop =0;
  14.        return false;
  15.      }
  16.      loop++;
  17.      
  18.          if((length == 1 || length ==0 ) && loop > 0)
  19.               return true;
  20.          else{
  21.              if(word.charAt(0) == word.charAt(length-1) )            
  22.                  return checkPalindrome(word.substring(1,length-1));
  23.              loop =0;
  24.              return false;            
  25.          }
  26.      }
  27.  
  28.    public static Set<String> permute(String chars)
  29.    {
  30.  
  31.      Set<String> set = new TreeSet<String>();
  32.  
  33.      if (chars.length() == 1)
  34.      {
  35.        set.add(chars);
  36.      }
  37.      else
  38.      {
  39.  
  40.        for (int i=0; i<chars.length(); i++)
  41.        {
  42.  
  43.          String pre = chars.substring(0, i);
  44.          String post = chars.substring(i+1);
  45.          String remaining = pre+post;
  46.  
  47.  
  48.          for (String permutation : permute(remaining))
  49.          {
  50.  
  51.            set.add(chars.charAt(i) + permutation);
  52.          }
  53.        }
  54.      }
  55.      return set;
  56.    }
  57.  
  58.    public static void compute_palindromes(String[] s){
  59.     int i;
  60.     for (i=0;i<s.length;i++){
  61.     boolean check =false;
  62.     for (String str : Palindrome.permute(s[i])){
  63.      
  64.      check =  checkPalindrome(str);
  65.      if(check == true){
  66.       System.out.println(s[i]+":"+str);
  67.       break;
  68.      }
  69.      
  70.      
  71.          }
  72.     if(check ==false){
  73.      System.out.println(s[i]+":1");
  74.     }
  75.  
  76.   }
  77.    
  78.    }
  79.    
  80.    public static void main(String[] args){
  81.     String[] words = {"ivcci","oyotta","bbb","babbb"};
  82.     compute_palindromes(words);
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement