# 937 Reorder Data in Log Files

請熟記 String Method,substr 、 localeCompare、 indexOf 跟 Array sort

LeetCode

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.

digit-log = identifier + 小寫字母組成
letter-logs = identifier + 數字組成
至少有一個字
請排序 letter-logs + digit-log
letter-logs 不看第一個 word 其他按照 a-z 排,digit-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"] 

Constraints:

0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] is guaranteed to have an identifier, 
and a word after the identifier.

怎麼解

  • 先判斷是 digit-log 還是 letter-logs

  • letter-logs就去抓第 2 個 word 排序

  • digit-log 就是 queue 抓到存,最後再 concat 到 letter-logs

var reorderLogFiles = function(logs) {
  let digitArr = [];
  let letterArr = []
  logs.forEach(log => {
    let x = 0
    while(log[x]!==' '){
        x++;
    }
    // console.log(Number(log[x + 1]))
    if(Number(log[x + 1]) == log[x + 1]){
      digitArr.push(log);
    }else{
      letterArr.push(log)
    }
  })
  letterArr.sort( (a, b) => {
    let strA = a.substr(a.indexOf(' ') + 1);
    let strB = b.substr(b.indexOf(' ') + 1);
    if(strA === strB) return a.localeCompare(b);
    return strA.localeCompare(strB);
  })
  return [...letterArr, ...digitArr]
};

學到什麼?

這題速度只有 58% 不太好,但發現自己對於 String Method 很不熟導致有想法也不知道怎麼寫.需要熟記 String Method 以及 sort 使用方式,有時間再回來想想怎麼寫會更好

Last updated