937. Reorder Log Files(python+cpp)
題目:
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;
}
};
總結: