Leetcode-937-Reorder Log Files-(Easy)

一、題目描述

  

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:

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

  解釋:

  給定一個字符串的數組,每個字符串中間用空格分割,第一個元素表示索引,後面的爲內容;內容分爲兩種,一種是純字符串,一種是純數組

  要求進行排序,排序規則是,純字符串內容的排在純數字的前面;對於純字符串的元素,比較索引大小排序;對於純數字的其相對位置不變

  

二、解答:

class Solution {
public:
static bool cmp(const string &A, const string& B){
    string subA = A.substr(A.find(' ') + 1);
    string subB = B.substr(B.find(' ') + 1);
    if(isdigit(subA[0]))
        return false;
    else if(isdigit(subB[0]))
        return true;
    return subA.compare(subB) < 0;
}

public:
    vector<string> reorderLogFiles(vector<string>& logs) {
        
        stable_sort(logs.begin(), logs.end(), cmp);

        return logs;
    }
};


int main(int argc, char **argv)
{
	Solution *s = new Solution();
	cout<<""<<endl;

    return 0;
}

 

三、學習到的方法

  sort使用的快速排序;stable_sort使用的是merge排序,穩定的,意思是相等的元素前後的位置會保持

  

 

  另外,string的兩個方法

  1、substr(index) ,從0到index的子串

  2、find('') ,表示尋找某個字符所在的位置

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章