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: 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"]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class ReorderDataLogFiles {public static void main(String[] args) {String[] logs = { "dig1 8 1 5 1", "let1 art can", "dig2 3 6","let2 own kit dig", "let3 art zero" };String[] reorder = reorderLogFiles(logs);System.out.println(Arrays.toString(reorder));}static String[] reorderLogFiles(String[] logs) {if (logs.length <= 1) {return logs;}List<String> l1 = new ArrayList<>();List<String> l2 = new ArrayList<>();for (String s : logs) {int i = s.indexOf(" ");if (Character.isDigit(s.charAt(i + 1))) {l2.add(s);} else {l1.add(s);}}Collections.sort(l1, new Comparator<String>() {@Overridepublic int compare(String s1, String s2) {int i = s1.indexOf(" ");int j = s2.indexOf(" ");int temp = s1.substring(i + 1).compareTo(s2.substring(j + 1));if (temp == 0) {return s1.substring(0, i).compareTo(s2.substring(0, i));}return temp;}});String[] res = new String[l1.size() + l2.size()];int k = 0;for (String s : l1) {res[k++] = s;}for (String s : l2) {res[k++] = s;}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function used as comparator in sortingstatic bool cmp(string a, string b){int pos1 = a.find(' ');int pos2 = b.find(' ');if (a.substr(pos1 + 1) < b.substr(pos2 + 1))return true;if (a.substr(pos1 + 1) > b.substr(pos2 + 1))return false;elsereturn a.substr(0, pos1 + 1) < b.substr(0, pos2 + 1);}vector<string> reorderLogFiles(vector<string> &logs){int n = logs.size();vector<string> v1, v2;for (auto i : logs){if (isdigit(i[i.find(' ') + 1]))v2.push_back(i);elsev1.push_back(i);}sort(v1.begin(), v1.end(), cmp);for (int i = 0; i < v2.size(); i++)v1.push_back(v2[i]);return v1;}int main(){vector<string> logs = {"dig1 8 1 5 1", "let1 art can", "dig2 3 6","let2 own kit dig", "let3 art zero"};vector<string> reorder = reorderLogFiles(logs);cout << "[";for (int i = 0; i < reorder.size() - 1; i++)cout << reorder[i] << ", ";cout << reorder[reorder.size() - 1] << "]";return 0;}
No comments:
Post a Comment