Monday, May 29, 2017

Permutation of a String

import java.util.ArrayList;
import java.util.List;

public class PermuationStrings {
    static List<String> list=new ArrayList<String>();
    public static void main(String args[]) {
        list=permuteString("cat");
        System.out.println("All Permutations are: "+list);
        System.out.println("Count: "+list.size());
    }
    public static List<String> permuteString(String stringValue) {
        return permuteString("",stringValue);
    }

    private static List<String> permuteString(String begin, String end) {
        if(end.length() <= 1) {
            list.add(begin + end);
        } else {
            char ch=' ';
            for(int i = 0; i < end.length(); i++) {
                try {
                    //cat.substring(1) meant at.
                    String newString = end.substring(0, i) + end.substring(i + 1);   
                    ch = end.charAt(i);
                    System.out.println("B:"+begin+",   Ch:"+end.charAt(i)+",   N:"+newString);
                    permuteString(begin+ch, newString);   //In first iteration: permuteString(c, at)
                    //In Second iteration: permuteString(ca, t)
                } 
                catch (StringIndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}
//Output
B:,   Ch:c,   N:at
B:c,   Ch:a,   N:t
B:c,   Ch:t,   N:a
B:,   Ch:a,   N:ct
B:a,   Ch:c,   N:t
B:a,   Ch:t,   N:c
B:,   Ch:t,   N:ca
B:t,   Ch:c,   N:a
B:t,   Ch:a,   N:c
All Permutations are: [cat, cta, act, atc, tca, tac]
Count: 6

//To check Palindrome
public static boolean checkIfPalindrome(String original) {
    int length = original.length();
    String reverse="";
    for(int i = length - 1; i >= 0; i--) {
        reverse = reverse + original.charAt(i);
    }
    if(original.equals(reverse)){
        System.out.print(", Yes Palindrome: "+original);
        return true;
    }else{
        System.out.print(", No Palindrome: "+original);
    }
    return false;
}
public static boolean checkIfPalindromNumber(int number){
    int r,sum=0,temp;    
    int n=454;//It is the number variable to be checked for palindrome  
    temp=n;    
    while(n>0){    
        r=n%10;  //Getting remainder  
        sum=(sum*10)+r;    
        n=n/10;    
    }    
    if(temp==sum)    
        return true;    
    else    
        return false;    
}  

No comments:

Post a Comment