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.
题目理解:
给定一系列记录(log),每一个记录由标题和内容组成,字符串的第一个子串是标题,后面的是内容。记录分为两种,一种是字符型记录,其内容完全由小写字母组成,另一种是数字型记录,其内容完全由数字组成。现在要将这些记录排序然后输出。字符型记录排在数字型记录的前面。字符型数据按照内容的字母顺序排序,如果内容相同,则按照标题排序。数字型记录按照原本的顺序不变。
解题思路:
因为字符型数据的内容全部由小写字母组成,因此可以根据最后一个字符是不是小写字母来区分字符型记录和数字型记录。对于字符型记录,使用一个数据结构存储,存储其标题和内容,最后按照要求排序。数字型数据直接记录下来。
代码如下:
class Solution {
class node implements Comparable<node>{
String id;
String content;
public node(String i, String c) {
id = i;
content = c;
}
@Override
public int compareTo(node o) {
// TODO Auto-generated method stub
if(content.equals(o.content))
return id.compareTo(o.id);
return content.compareTo(o.content);
}
}
public String[] reorderLogFiles(String[] logs) {
List<String> digit = new ArrayList<String>();
List<node> letter = new ArrayList<node>();
for(String str : logs) {
char ch = str.charAt(str.length() - 1);
if(ch < '0' || ch > '9') {
int pos = str.indexOf(' ');
letter.add(new node(str.substring(0, pos), str.substring(pos + 1)));
}
else
digit.add(str);
}
Collections.sort(letter);
int it = 0;
for(node cur : letter) {
logs[it++] = cur.id + " " + cur.content;
}
for(String str : digit)
logs[it++] = str;
return logs;
}
}