leecode 937 Reorder Log Files (模擬)
傳送門:點我
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 its identifier.
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 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","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.
大意:給你一些日誌,包括英文日誌和數字日誌,每個日誌又包括日誌頭和日誌內容,日誌頭是第一個單詞,日誌內容全數字的是數字日誌,全英文的是英文日誌。要求排序後輸出。
排序規則:對英文的日誌,去掉日誌頭,按日誌內容字典序排序。對數字的日誌,按輸入順序。
總體上,英文日誌在前,數字日誌在後。
思路:對每個字符串的最後一位進行判斷之後,分類到兩個向量裏,對英語日誌用stringstream進行分割,然後sort排序。
代碼:
class Solution { public: static bool cmp(string s1,string s2){ string news1="",news2=""; stringstream ss1(s1); string s; int k = 0; while(ss1>>s){ if(k > 0){ news1 = news1 + s +" "; } k++; } k = 0; stringstream ss2(s2); while(ss2>>s){ if(k > 0){ news2 = news2 + s +" "; } k++; } if(news1<news2) return true; return false; //return news1 < news2; } vector<string> reorderLogFiles(vector<string>& logs) { vector<string>p1,p2,ans; for(int i = 0 ; i < logs.size() ; i++){ string s = logs[i]; if(s[s.size()-1]<=‘9‘ && s[s.size()-1] >= ‘0‘){ p2.push_back(s); } else{ p1.push_back(s); } } sort(p1.begin(),p1.end(),cmp); for(int i = 0 ; i < p1.size() ; i ++){ ans.push_back(p1[i]); } for(int i = 0 ; i < p2.size() ; i ++){ ans.push_back(p2[i]); } return ans; } };
leecode 937 Reorder Log Files (模擬)