zoukankan      html  css  js  c++  java
  • 字符串取反问题

    问题:将字符串取反。

    例如,“abcd” ---> "dcba"

    这里的思想取自合并排序。下面的源码存在一个问题。目前我还没有解决掉,欢迎大家指导!!

     1 /* 
     2  * Q: 将字符串取反。例如,
     3  * “abcd” --> "dcba"
     4  */
     5 #include <iostream>
     6 #include <cstring>
     7 
     8 using namespace std;
     9 
    10 void Merge(char *str, int start, int mid, int end)
    11 {
    12     int lenleft = mid - start + 1;
    13     int lenright = end - mid;
    14     char *pleft = new char[lenleft + 1];
    15 
    16     strncpy(pleft, str + start -1, lenleft);
    17     strncpy(str + start - 1, str + mid, lenright);
    18     strncpy(str + start + lenright - 1, pleft, lenleft);
    19 
    20     delete[] pleft;
    21 }
    22 
    23 /* 
    24  * 有一个BUG:需要在最后的时候加一个空格!
    25  * 因为在转换过程中,删掉了最后一个字符。
    26  */
    27 void MergeString(char *str, int start, int end)
    28 {
    29     if (start < end) {
    30         int mid = (start + end) / 2;
    31 
    32         MergeString(str, start, mid);
    33         MergeString(str, mid + 1, end);
    34         Merge(str, start, mid, end);
    35   //      cout << str << endl;
    36     }
    37 }
    38 
    39 int main()
    40 {
    41     char str[] = "abcd ";
    42 
    43     cout << "Before: \n" << str << endl;
    44 
    45     cout << "\nin service: \n";
    46     MergeString(str, 0, strlen(str));
    47 
    48     cout << "\nAfter: \n" << str << endl;
    49 
    50     return 1;
    51 }
  • 相关阅读:
    POJ 3268 Silver Cow Party (Dijkstra)
    怒学三算法 POJ 2387 Til the Cows Come Home (Bellman_Ford || Dijkstra || SPFA)
    CF Amr and Music (贪心)
    CF Amr and Pins (数学)
    POJ 3253 Fence Repair (贪心)
    POJ 3069 Saruman's Army(贪心)
    POJ 3617 Best Cow Line (贪心)
    CF Anya and Ghosts (贪心)
    CF Fox And Names (拓扑排序)
    mysql8.0的新特性
  • 原文地址:https://www.cnblogs.com/life91/p/2975779.html
Copyright © 2011-2022 走看看