830. String Sort

830. String Sort

answer

int alpha[256] = {0};//记录字符的次数 
bool cmp(char a,char b)
{
    if(alpha[a]==alpha[b])//如果次数相同 
    {
        return a<b;
    }
    return alpha[a]>alpha[b];
}

class Solution {
public:
    /**
     * @param str: the string that needs to be sorted
     * @return: sorted string
     */
    
    string stringSort(string &str) {
        // Write your code here
        memset(alpha,0,sizeof(alpha)*sizeof(int));
        //统计各字符出现次数 
        for(int i=0;i<str.length();i++)
        {
            alpha[str[i]]++;
        }
        
        sort(str.begin(),str.end(),cmp);
        return str;
    }
};

Encounter problems

Input
"lintcode"

Output
"oelcdint"

Expected
"cdeilnot"

This is because of the lack of memset statement did not initialize an array of alpha, indicating the OJ write in class Solution external variables are initialized manually.

to sum up

  • Use standard library sort function is very convenient, but it will lower the efficiency of some. When finish data 151ms.
  • Understanding cmp (p1, p2), the inner top surface cmp function returns true p1, p2 false on the top surface

Guess you like

Origin www.cnblogs.com/virgildevil/p/12155675.html