leetcode 937. Reorder Log Files (簡單模擬)
阿新 • • 發佈:2018-12-26
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]
思路: 將第一小段去掉後,判斷第一個字元是字母還是數字。
若是數字,直接放到一個vector裡面即可
若是字母,只保留後面部分,並建立map對映關係
最後,排序,輸出即可。
程式碼:
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
class Solution {
public:
vector<string> reorderLogFiles(vector<string>& logs) {
vector<string> vec1,vec2;
int n=logs.size();
map<string,string> mp;
mp.clear();
for(int i=0;i<n;i++)
{
int j=0;
while(logs[i][j]!=' ')
{
j++;
}
while(logs[i][j]==' ')
{
j++;
}
if(logs[i][j]>='0'&&logs[i][j]<='9')
{
vec1.push_back(logs[i]);
}
else
{
string tmp;
for(int k=j;k<logs[i].size();k++) tmp.push_back(logs[i][k]);
mp[tmp] = logs[i];
vec2.push_back(tmp);
}
}
sort(vec2.begin(),vec2.end());
vector<string> ans;
for(auto &t: vec2) {
ans.push_back(mp[t]);
}
for(auto &t : vec1) ans.push_back(t);
return ans;
}
};