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"]
由题意可知,每个字符串的第一位是标识符,如果日志后面为字母,则代表是字母日志,要将字母日志按字母的升序排序,如果在字母日志相同的情况下,按标识符顺序排列。数字日志不排序,按出现的先后顺序拼接到字母日志后面。
首先,先将字母日志跟数字日志区分,存到不同的两个ArrayList中,再对存放字母日志的List进行排序,最后将数字日志List拼接到字母日志List后面。百度时有两种方法对字母日志排序,一种是使用TreeMap(按照键值大小排序),但是在键值大小一样的情况下会出错。贴上我的方法:
class Solution {
public String[] reorderLogFiles(String[] logs) {
ArrayList<String> str1 = new ArrayList<String>();
ArrayList<String> str2 = new ArrayList<String>();
for(int i =0;i< logs.length;i++ )
{
String[] stunum=new String[2];
stunum = logs[i].split(" ",2);
if(stunum[1].charAt(0) >= 'a'&& stunum[1].charAt(0)<='z')
{
str1.add(logs[i]);
}
if(stunum[1].charAt(0) >= '0'&& stunum[1].charAt(0)<='9')
{
str2.add(logs[i]);
}
}
Collections.sort(str1, (o1, o2) -> { //重写sort方法,在字母日志一样的情况下,按照标识排序;
int indexo1 = o1.indexOf(" ");
int indexo2 = o2.indexOf(" ");
String flago1 = o1.substring(0,indexo1); //取标识
String flago2 = o2.substring(0,indexo2);
String substro1 = o1.substring(indexo1+1); //取字母日志
String substro2 = o2.substring(indexo2+1);
if(substro1.compareTo(substro2)==0)
{
return flago1.compareTo(flago2);
}
return substro1.compareTo(substro2);
});
str1.addAll(str2); //将数字日志拼接到字母日志后面
String[] result = str1.toArray(new String[str1.size()]);
return result;
}
}
Runtime: 35 ms, faster than 36.43% of Java online submissions for Reorder Log Files.
Memory Usage: 38.6 MB, less than 69.68% of Java online submissions for Reorder Log Files.
结果不优,但总算通过了。