Saturday, 31 January 2015

Check if two strings are permuatations of eachother

public static boolean permutation (String s, String t)
{
    //  check if they are of same lenght
    if( s.lenght() != t.length() )
    {
        return false;
    }
   
    int letters [] = new int[128] ; // for ASCII strings
   
    char[] s_array = s.toCharArray();
   
    for( char c : s_array)// count number of each character in s
    letters[c]++;
   
    for( int i = 0 ; i < t.length() ; ++i)
    {
        int c = (int) t.charAt(i);
        if(--letters[c] < 0 )
        return false
    }
    return true;
}

No comments:

Post a Comment