Wednesday, July 18, 2012

String Anagram Algorithm

As a continuation of the last post, here is an algorithm for finding anagrams from a string
public class Anag {



        public static void main(String args[]){

                char[] anag = new char[args[0].length()];
                findAnag(args[0], new String(anag), 0);




        }



        public static void findAnag(String orig, String anag, int index) {
                if ( orig.toCharArray().length == 0 ) {

                        System.out.println( anag );
                        return;


                }

                char[] origChars = orig.toCharArray();
                char[] anagChars = anag.toCharArray();

                for( int i=0; i < origChars.length; i++ ) {

                        anagChars[index] = origChars[i];
                        index++;
                        String strStillLeft = orig.substring(0, i) + orig.substring(i+1, orig.length());
                        findAnag( strStillLeft, new String(anagChars), index);
                        index--;

                }




        }











}

https://github.com/asharif/StringAnag

No comments:

Post a Comment