Saturday, October 3, 2015

[1.4] Decide if two strings are anagrams or not

1. Example

s1= "bottle"
s2= "lebott"

2. Implementation


// Time:O(n log n), Space:O(n) for sorting
public static boolean anagram(String s , String t)
{ 


     //validate the input
     if (s.length() != t.length())
         return false;


     String sortedS = new String(Arrays.sort(s.toCharArray()));
     String sortedT = new String(Arrays.sort(t.toCharArray()));
     return sortedS == sortedT;


}



// NOTE: In order not to check all letters[256] to see if any on 
// of it is not Zero. Use num_unique_chars and num_completed_t 
public static boolean anagram(String s, String t)
{


      
    
     // validate the input
     if ( s.length() != t.length() )
         return false;



     int[] letters = new int[256];
     int num_unique_chars = 0;
     int num_completed_t = 0;
     char[] s_array = s.toCharArray();


     
     for (char c: s_array)
     {
          if(letters[c]==0) ++num_unique_chars;
          ++letters[c];
     }




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



        int c = (int) t.charAt(i);
        if ( letters[c] == 0 )
            return false;


        --letters[c];
        if ( letter[c] == 0) 
        {
            ++num_completed_T;
            // NOTE: completed == unique AND is last character
            if (  num_completed_t == num_unique_chars  )
            { 
                // it's a match if t has been processed completely
                
                return i == t.length() -1;
            }
        }
      

        
    }



    return false;



}

3.Similar Ones

No comments:

Post a Comment