跳到主要内容

937.重新排列日志文件

链接:937.重新排列日志文件
难度:Medium
标签:数组、字符串、排序
简介:返回日志的最终顺序。

题解 1 - cpp

  • 编辑时间:2022-03-24
  • 执行用时:60ms
  • 内存消耗:32.3MB
  • 编程语言:cpp
  • 解法介绍:遍历后比较。
vector<string> split(string str) {
istringstream iss(str);
string tmp;
vector<string> ans;
while (getline(iss, tmp, ' ')) ans.push_back(tmp);
return ans;
}
bool comp(string &a, string &b) {
vector<string> list1 = split(a), list2 = split(b);
string body1 = "", body2 = "";
for (int i = 1; i < list1.size(); i++) body1 += list1[i] + " ";
for (int i = 1; i < list2.size(); i++) body2 += list2[i] + " ";
if (body1 == body2)
return list1[0] < list2[0];
else
return body1 < body2;
}
class Solution {
public:
vector<string> reorderLogFiles(vector<string> &logs) {
vector<string> lets, digs, ans;
for (auto &log : logs) {
if (isDigLog(log))
digs.push_back(log);
else
lets.push_back(log);
}
sort(lets.begin(), lets.end(), comp);
for (auto &log : lets) ans.push_back(log);
for (auto &log : digs) ans.push_back(log);
return ans;
}
bool isDigLog(string log) { return isdigit(split(log)[1][0]); }
};

题解 2 - cpp

  • 编辑时间:2022-05-03
  • 执行用时:4ms
  • 内存消耗:4.6MB
  • 编程语言:cpp
  • 解法介绍:分割字符串,排序。
type Item struct {
raw []string
state int
idx int
}
func reorderLogFiles(logs []string) []string {
n := len(logs)
list := make([]Item, n)
for i := 0; i < n; i++ {
list[i] = toItem(logs[i], i)
}
sort.Slice(list, func(i, j int) bool {
if list[i].state == 0 && list[j].state == 0 {
return list[i].idx < list[j].idx
} else if list[i].state == 0 && list[j].state == 1 {
return false
} else if list[i].state == 1 && list[j].state == 0 {
return true
} else {
idx := 1
for ; idx < len(list[i].raw) && idx < len(list[j].raw); idx++ {
comp := strings.Compare(list[i].raw[idx], list[j].raw[idx])
if comp < 0 {
return true
} else if comp > 0 {
return false
}
}
if idx != len(list[i].raw) {
return false
} else if idx != len(list[j].raw) {
return true
} else {
return strings.Compare(list[i].raw[0], list[j].raw[0]) < 0
}
}
})
ans := make([]string, n)
for i, val := range list {
ans[i] = logs[val.idx]
}
return ans
}
func toItem(log string, i int) Item {
item := Item{}
item.idx = i
item.raw = strings.Split(log, " ")
var flag bool = true
for _, val := range item.raw[1] {
if !unicode.IsDigit(val) {
flag = false
break
}
}
if flag {
item.state = 0
} else {
item.state = 1
}
return item
}