public class Solution
    {
        public string[] ReorderLogFiles(string[] logs)
        {
            var list1 = new List<string>();
            var list2 = new List<string>();
            foreach (var log in logs)
            {
                var spacePosition = log.IndexOf(' ');
                var c = log[spacePosition + 1];
                if (c >= 48 && c <= 57)
                {
                    list2.Add(log);
                }
                else
                {
                    list1.Add(log);
                }
            }
            var list = list1.OrderBy(x => x.Substring(x.IndexOf(' ') + 1)).ToList();
            list.AddRange(list2);
            return list.ToArray();
        }
    }

 补充一份C++的实现:

bool cmp(const pair<string, string>& a, const pair<string, string>& b) {
    return a.second < b.second;
}
class Solution {
public:    
    vector<string> reorderLogFiles(vector<string>& logs) {        
        map<string, string> V1;//记录文本log
        vector<string> V2;//记录数字log
        for (auto log : logs) {
            int spacePosition = 0;
            for (int i = 0; i < log.length(); i++) {
                if (log[i] == ' ') {
                    spacePosition = i;//找到第一个空格的下标
                    break;
                }
            }
            char c = log[spacePosition + 1];//找到空格后第一个字符
            if (c >= 48 && c <= 57) {//ASCII码在48~57,表示数字0~9
                V2.push_back(log);//存储数字log
            }
            else {
                //Key值是原始log,Value值是去除头部的identifier之后的内容
                V1.insert(make_pair(log, log.substr(spacePosition + 1)));                                
            }                            
        }
        //将map转换为vector
        vector<pair<string, string>> vec(V1.begin(), V1.end());

        //按照value值排序
        sort(vec.begin(), vec.end(), cmp);

        vector<string> V;//记录最终结果
        for (auto p : vec) {
            V.push_back(p.first);
        }
        for (auto p : V2) {
            V.push_back(p);
        }
        return V;
    }
};

int main()
{
    Solution S;
    vector<string> V;    
    V.push_back("a1 9 2 3 1");
    V.push_back("g1 act car");
    V.push_back("zo4 4 7");
    V.push_back("ab1 off key dog");
    V.push_back("a8 act zoo");
    vector<string> V2 = S.reorderLogFiles(V);
    for (auto v : V2) {
        cout << v << endl;
    }
}

 提交显示错误的问题,我这里没有遇到,截图如下:

posted on 2018-11-12 15:37  Sempron2800+  阅读(300)  评论(5编辑  收藏  举报