937. Reorder Log Files(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83987355

题目:

You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
 Each word after the identifier will consist only of lowercase letters,or;
 Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after itsidentifier.
Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order. Return the final order of the logs.
Example 1:

Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 actzoo"] 
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 31","zo4 4 7"]  

Note:

0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] is guaranteed to have an identifier, and a word after the identifier.

解释:
用python很好实现,用c++感觉很难的样子,排序的时候是不是需要hashMap?
python代码:

class Solution:
    def reorderLogFiles(self, logs):
        """
        :type logs: List[str]
        :rtype: List[str]
        """
        result=[]
        toSort=[]
        for log in logs:
            log=log.split(' ')
            if log[1].isdigit():
                result.append(' '.join(log))
            else:
                toSort.append(log)
        toSort=sorted(toSort,key=lambda x:x[1:])
        toSort=[' '.join(x) for x in toSort]
        result=toSort+result
        return result

c++需要自己写比较函数,并且用stable_sort,韦德是当第一个元素是数字的情况下,不改变其原来的相对次序。一定要用稳定排序。
c++代码:

class Solution {
public:
    static bool cmp(string A, string B){
    string subA = A.substr(A.find(' ') + 1);
    string subB = B.substr(B.find(' ') + 1);
    if(isdigit(subA[0]))
        return false;
    else if(isdigit(subB[0]))
        return true;
    return subA.compare(subB) < 0;
    }

    vector<string> reorderLogFiles(vector<string> &logs) {
        stable_sort(logs.begin(), logs.end(), cmp);
        return logs;
    }  
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83987355
今日推荐