LintCode 819. 单词排序

给一个新的字母表,如{c,b,a,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z},根据新的字母表排序字符串数组。

 注意事项
  • 输入的单词长度不超过100
  • 输入的单词总数不超过10000
  • 可以认为,输入的新字母表即一个长度为26的字符串
  • 保证题目只会出现小写字母

样例

给出 Alphabet = {c,b,a,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}, String array = {cab,cba,abc}, 返回 {cba,cab,abc}

解释:
根据新的字典序,排序输出{cba,cab,abc}。

给出 Alphabet = {z,b,a,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,c}, String array = {bca,czb,za,zba,ade}, 返回 {zba,za,bca,ade,czb}

解释:
根据新的字典序,排序输出{zba,za,bca,ade,czb}。

 

思路:相当于对于字符串的大小重定义,很快能想到的一个办法是写一个比较函数然后扔给std::sort去排序,但这里的比较函数需要包含比较字典的信息才能进行,好像只能自己写个快排才能完成,而且类内写比较函数要注意this指针,只能用static函数,这个需要注意一下。比较字典我这里用了一个最简单的数组,这么小规模的数据如果用hash结构unordered_map好像有点大材小用,最后就是string_comp这个函数了

 1 class Solution {
 2 public:
 3     /**
 4      * @param alphabet: the new alphabet
 5      * @param words: the original string array
 6      * @return: the string array after sorting
 7      */
 8     vector<string> wordSort(string &alphabet, vector<string> &words) {
 9         // Write your code here
10         for(int i = 0; i<26 ;++i){//构建字典,存在private字段里
11             dict[alphabet[i]-'a'] = i;
12         }
13         vector<string> res = words;
14         QuickSort_vector_index(res,0,words.size()-1);
15         return res;
16     }
17     
18     bool string_comp(string s1,string s2){//比较函数,注意只有当s1<s2是返回true
19         int size1 = s1.size();
20         int size2 = s2.size();
21         for(int i = 0; i<min(size1,size2); ++i){
22             if(dict[s1[i]-'a']<dict[s2[i]-'a']) return true;
23             else if(dict[s1[i]-'a']==dict[s2[i]-'a']) continue;
24             else return false;
25         }
26         if(size2>size1) return true;
27         return false;
28     }
29     
30     void QuickSort_vector_index(vector<string> &words,int start ,int end){//改造过的快排。。。有点意思的
31         if(start>=end) return;
32         string temp = words[start];
33         int L = start; //L,R左右哨兵
34         int R = end;
35         while(L<R){
36             while(L<R && !string_comp(words[R],temp)) //找到右侧第一个比temp小的数 放到左侧挖的坑里面去
37                 R--;
38             if(L<R) //注意一定要增加L<R这个判断语句
39                 words[L++] = words[R];
40             while(L<R && !string_comp(temp,words[L]))
41                 L++;
42             if(L<R)
43                 words[R--] = words[L];
44         }
45         words[L] = temp; //中间的坑填上中间量
46         QuickSort_vector_index(words,start,L-1);
47         QuickSort_vector_index(words,L+1,end);
48     }
49 private:
50     int dict[26]={0};
51 };

 

posted @ 2018-04-12 19:44  J1ac  阅读(298)  评论(0编辑  收藏  举报