zoukankan      html  css  js  c++  java
  • 翻转句子中单词的顺序 【微软面试100题 第十题】

    题目要求:

      输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。

      例如:输入"I am a student.",则输出"student. a am I".

      参考资料:剑指offer第42题。

    题目分析:

      1.实现一个翻转函数;

      2.先翻转整个句子,再翻转句子中的每个单词。

    代码:

    #include <iostream>
    
    using namespace std;
    
    char *reverseSentence(char *p);
    
    int main(void)
    {
        char a[] = "I am a student.";
        cout << "原句子:" << a << endl;
        reverseSentence(a);
        cout << "翻转后的句子:" << a << endl;
        return 0;
    }
    void reverse(char *s,char *e)
    {
        if(s==NULL || e==NULL)
            return ;
        while(s<e)
        {
            char temp = *s;
            *s = *e;
            *e = temp;
            s++;
            e--;
        }
    }
    char *reverseSentence(char *p)
    {
        if(p == NULL)
            return NULL;
    
        char *begin = p;
        char *end = p;
    
        while(*end != '')
            end++;
        end--;
    
        reverse(begin,end);
    
        begin = end = p;
        while(*begin != '')
        {
            if(*begin == ' ')
            {
                begin++;
                end++;
            }
            else if(*end==' ' || *end=='')
            {
                reverse(begin,--end);
                begin = ++end;
            }
            else
                end++;
        }
        return p;
    }
    View Code
  • 相关阅读:
    python 之os模块用法大全
    web自动化测试常用的定位方式有哪些?
    Jenkins
    吴恩达机器学习笔记:如何debug一个学习算法?
    贝叶斯网络
    leetcode-32. Longest Valid Parentheses
    leetcode4 median Of two sorted array
    leetcode21
    vs2017问题集锦
    LIS
  • 原文地址:https://www.cnblogs.com/tractorman/p/4055172.html
Copyright © 2011-2022 走看看