zoukankan      html  css  js  c++  java
  • IT公司100题-10-翻转句子中单词的顺序

    问题描述:
    输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
    句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
    例如输入“Hello world!”,则输出“world! Hello”。
     
    分析:
     
    先翻转各个单词,然后整体翻转即可。
     

    参考代码

     1 // 10.cc
     2 #include <iostream>
     3 #include <cstring>
     4 #include <string>
     5 using namespace std;
     6 
     7 void reverse(char* p_start, char* p_end) {
     8     char t;
     9     while(p_start < p_end) {
    10         t = *p_start;
    11         *p_start = *p_end;
    12         *p_end = t;
    13 
    14         p_start++;
    15         p_end--;
    16     }
    17 }
    18 
    19 char* reverse_str(char* str) {
    20     if (NULL == str)
    21         return NULL;
    22 
    23     char* p_start = str;
    24     char* p_end = str;
    25 
    26     // 翻转每个单词
    27     while(*p_start != '') {
    28         if(*p_start == ' ') {
    29             p_start++;
    30             p_end++;
    31         } else if (*p_end == ' ' || *p_end == '') {
    32             reverse(p_start, --p_end);
    33             p_start = ++p_end;
    34         } else {
    35             p_end++;
    36         }
    37     }
    38 
    39     p_end = --p_start;
    40     p_start = str;
    41     // 整体翻转
    42     reverse(p_start, p_end);
    43 
    44     return str;
    45 }
    46 
    47 int main() {
    48     cout << "input a string:" << endl;
    49     string s;
    50     getline(cin, s);
    51     char *p = new char[s.size() + 1];
    52     strcpy(p, s.c_str());
    53     reverse_str(p);
    54     cout << p << endl;
    55 
    56     delete []p;
    57     return 0;
    58 }

    自己的代码:

     1 char* reverse_str(const char* s1)
     2 {
     3     assert(s1);
     4     stack<char> stack1;
     5     const char* head = s1, *rear = s1;
     6     while (*head != '')
     7     {
     8         while(*head != ' ' && *head != '')
     9             head++;
    10 
    11         const char* p;
    12         for(p=head-1;p>=rear;p--)
    13                 stack1.push(*p);
    14 
    15         if(*head == ' ')
    16             stack1.push(' ');
    17         if(*head != '')
    18             rear = ++head;
    19     }
    20     char * return_v = new char[strlen(s1)+1];
    21     int i=0;
    22     while(!stack1.empty())
    23     {
    24         return_v[i++] = stack1.top();
    25         stack1.pop();
    26     }
    27     return_v[i]='';
    28     return return_v;
    29 }

    转载自源代码

    本文链接地址: http://w.worthsee.com/index.php/10-%e7%bf%bb%e8%bd%ac%e5%8f%a5%e5%ad%90%e4%b8%ad%e5%8d%95%e8%af%8d%e7%9a%84%

  • 相关阅读:
    【Windows】netsh动态配置端口转发
    Python 脚本注册为Windows Service
    【Windows】Python脚本随机启动
    【MySQL】CSV 文件导入MySQL
    【Python】改变对象的字符串显示
    【Python】偏函数
    【Python】装饰器理解
    【Python】什么是闭包
    【Python】高阶函数介绍
    【Python】__all__ 暴露接口
  • 原文地址:https://www.cnblogs.com/dracohan/p/3899231.html
Copyright © 2011-2022 走看看