string path

package algorithm.weixin;

import java.util.Vector;

public class StringPath {
    public static final char[] voc = {'a', 'b', 'c', 'd', 'e', 'f', 'g',
                               'h', 'j', 'j', 'k', 'l', 'm', 'n',
                               'o', 'p', 'q', 'r', 's', 't', 'u',
                               'v', 'w', 'x', 'y', 'z'
                               };
    public static Vector<String> vec = new Vector<String>();
    public static void findStringPath( String s1, String s2, int len )
    {
        //for( int i = 0; i < len; i++ )
        {
            //singleChange( s1, s2, i, len );
            singleChange( s1, s2, 1, len );
        }
    }
    public static void singleChange( String s1, String s2, int pos, int len )
    {
        if( pos == len )
        {
            pos = 0;
        }
        if( s1 == s2 )
        {
            return;
        }

        char temp = s1.charAt(pos);
        char[] arr = s1.toCharArray();
        StringBuffer sb = new StringBuffer();
        for( int i = 0; i < 26; i++ )
        {
            if( voc[i] != temp )
            {
                arr[pos] = voc[i];
                String s = String.valueOf(arr);
                if( isValid( s ) )
                {
                    System.out.println( s );
                    singleChange( s, s2, pos+1, len );
                }
            }
        }
    }
    public static boolean isValid( String s )
    {
        return vec.contains(s);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        vec.add( "cat" );
        vec.add( "hat" );
        vec.add( "hot" );
        vec.add( "hog" );
        vec.add( "dog" );
        vec.add( "hag" );
        findStringPath( "cat", "dog", 3 );       
    }

}

result :

 

hat
hot
hog
dog

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s