问题:
难度:easy
说明:
感觉不像是 leetcode 的 easy 题,题目实际要求其实是:
输入给出一个 String[] ,日志里面都是 ' ' 空格字符隔开,只有 小写字母和 数字,空格隔开各个字符串都是 先小写字母 + 后数字, 然后 String[i] 第一个 空格前面的字符串 作为符号,将 符号后面的所有 空格以及字母字符 按照 ASCII码表排序,而将所有数字字符 的 排序认为比小写字母还要后,相当于 ASCII 码表里面,数字的码表值比 小写字母大:
"11 z0" 和 "11 zz" 排序就是 : "11 zz" "11 z0" : zz < z0,
而数字的权重都认为一样:"11 z1" "11 z0" 排序是 "11 z1" "11 z0" z1 == z0
题目连接:https://leetcode.com/problems/reorder-data-in-log-files/
输入范围:
1 <= logs.length <= 100
3 <= logs[i].length <= 100
- All the tokens of
logs[i]
are separated by a single space. -
logs[i]
is guaranteed to have an identifier and at least one word after the identifier.
输入案例:
Example 1:
Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Explanation:
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
Example 2:
Input: logs = ["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"]
我的代码:
其实思路是从 hash 得出,如果每个字符都算出hash,那么我就可以 一个快排 比较就 搞定,但是算 hash 没思路,但是 把字符串的 ascii 值排序改改倒是可以的。
相当于把 ASCII 的数字字符排的比字母字符更加后就行,而且数字排序值都一样,然后空格字符和字母字符本来顺序不用变,然后先比较后缀,如果后缀一样,就比较前缀这样处理就简单了。
Java:
class Solution {
private static char d = 'z';
public String[] reorderLogFiles(String[] logs) {
int len = logs.length, index = 1;
Node[] nodes = new Node[len];
for(int i = 0; i < len; i ++) {
int begin = logs[i].indexOf(" "), l = logs[i].length();
char[] hash = logs[i].substring(begin + 1, l).toCharArray(); // 思路根据 hash 的出来
char[] preHash = logs[i].substring(0, begin + 1).toCharArray();
Node node = new Node();
int l1 = hash.length, l2 = preHash.length;
for(int j = 0; j < l1; j ++) // 把所有数字都改成 z + 1 排序比字母后
if(hash[j] > ' ' && hash[j] < 'a') {
hash[j] = (char)(d + index ++); break;
}
for(int j = 0; j < l2; j ++)
if(preHash[j] > ' ' && preHash[j] < 'a') {
preHash[j] = (char)(d + index ++); break;
}
node.hash = new String(hash);
node.preHash = new String(preHash);
node.val = logs[i];
nodes[i] = node;
}
// 然后先排序后缀,再排序前缀
Arrays.sort(nodes, (o1, o2) -> o1.hash.equals(o2.hash) ? (o1.preHash.compareTo(o2.preHash)) : o1.hash.compareTo(o2.hash));
String res[] = new String[len];
for(int i = 0; i < len; i ++) res[i] = nodes[i].val;
return res;
}
}
class Node {
String val, hash, preHash;
}
C++:之后补上