My java answer with quicksort


  • 2
    N
    public class Solution {
    public boolean isAnagram(String s, String t) {
        
        if (s.length() != t.length())
            return false ;
         
        //convert string into char array
        char[] cs = s.toCharArray() ; 
        char[] ct = t.toCharArray() ;
        
        qsort(cs, 0, cs.length-1);
        qsort(ct, 0, ct.length-1);
        
        for(int i=0 ; i< cs.length ; i++){
            if(cs[i] != ct[i])
                return false ;
        }
        
        return true;
        
    }
    
    
    public void qsort(char[] c , int l , int r){
    	if(r<=l)
    		return ;
    		
    	int p = partition(c,l,r);
    	
    	qsort(c,l,p-1);
    	qsort(c,p+1,r);
    
    	
    }
    
    public int partition(char[] c, int l, int r){
    
    	int p = l-1;
    	
    	for(int i=l ; i<=r-1 ; i++){
    		if(c[i] < c[r]){
    			//swqp c[p+1] & c[i]
    			char tmp = c[p+1] ; 
    			c[p+1] = c[i];
    			c[i] = tmp;
    			
    			p++;
    		}
    	}
    	
    	//swqp c[p+1] & c[r]
    	char tmp = c[p+1] ; 
    	c[p+1] = c[r];
    	c[r] = tmp;
    	
    	return p+1 ;
    	
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.