[关闭]
@zsh-o 2018-03-25T06:50:00.000000Z 字数 1008 阅读 669

字符串排序 函数交换指针

算法


全部都是小写字母,小写字母重新组成一个顺序字典,然后根据这个字典进行字符串排序

题很简单,里面要用到一个用函数交换两个指针指向的内容,函数的参数需要是指针的指针string **p

  1. void exchange(string **a, string **b){
  2. string *t = *a;
  3. *a = *b;
  4. *b = t;
  5. }
  1. /**
  2. * in:
  3. * 5
  4. * bdceafghijklmnopqrstuvwxyz
  5. * abcde
  6. * adc
  7. * cda
  8. * cad
  9. * ddc
  10. * out:
  11. * ddc
  12. * cda
  13. * cad
  14. * abcde
  15. * adc
  16. * */
  17. #include <iostream>
  18. #include <vector>
  19. using namespace std;
  20. int DictTable[26];
  21. int get_order(char c){
  22. return DictTable[c-'a'];
  23. }
  24. int N;
  25. bool stringCompare(string &sa, string &sb){
  26. for(int i=0; i<min(sa.size(), sb.size()); i++){
  27. int ta = get_order(sa[i]);
  28. int tb = get_order(sb[i]);
  29. if(ta < tb)
  30. return true;
  31. else if(ta > tb){
  32. return false;
  33. }
  34. }
  35. return sa.size() > sb.size();
  36. }
  37. vector<string *> SL;
  38. void exchange(string **a, string **b){
  39. string *t = *a;
  40. *a = *b;
  41. *b = t;
  42. }
  43. void S_order(vector<string *> &pSL){
  44. for(int i=0; i<pSL.size(); i++){
  45. for(int j=i+1; j<pSL.size(); j++){
  46. if(stringCompare(*pSL[j], *pSL[i])){
  47. exchange(&pSL[i], &pSL[j]);
  48. }
  49. }
  50. }
  51. }
  52. int main(){
  53. cin>>N;
  54. char c;
  55. for(int i=0; i<26; i++){
  56. cin>>c;
  57. DictTable[c-'a'] = i;
  58. }
  59. for(int i=0; i<N; i++){
  60. string *s = new string;
  61. cin>>*s;
  62. SL.push_back(s);
  63. }
  64. S_order(SL);
  65. for(int i=0; i<SL.size(); i++){
  66. cout<<*SL[i]<<endl;
  67. }
  68. cin.get();
  69. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注