C a fast way to solve it


  • 0
    J

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>

    typedef struct com_node{

    char index;
    unsigned int num;
    

    }com_node_t;

    int compare_char(const void * num1,const void *num2){

    com_node_t * node1 = (com_node_t*)num1;
    com_node_t * node2 = (com_node_t*)num2;
    
    if(node1->num  < node2->num)return(1);
    if(node1->num  > node2->num)return(-1);
    return(0);
    

    }

    char* frequencySort(char* s) {

    int i = 0;
    com_node_t char_buf[128];
    memset(char_buf,0,sizeof(char_buf));
    
    unsigned int len = strlen(s);
    if(NULL == s)return(NULL);
    for(i=0;i<len;++i){
    	
    	char_buf[s[i]].index = s[i];
    	char_buf[s[i]].num += 1;
    }
    qsort(char_buf,128,sizeof(char_buf[0]),compare_char);
    
    int index_step = 0;
    int j = 0;
    for(i=0;i<128;++i){
    	
    	if(0 != char_buf[i].num){
    		
    		memset(s+index_step,char_buf[i].index,char_buf[i].num);
    		index_step += char_buf[i].num;
    	}	
    }
    return(s);
    

    }


Log in to reply
 

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