JZ-C-42

剑指offer第四十二题:翻转单词顺序:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变

  1 //============================================================================
  2 // Name        : JZ-C-42.cpp
  3 // Author      : Laughing_Lz
  4 // Version     :
  5 // Copyright   : All Right Reserved
  6 // Description : 翻转单词顺序:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变
  7 //============================================================================
  8 
  9 #include <iostream>
 10 #include <stdio.h>
 11 #include "StringUtil.h"
 12 #include <string.h>
 13 using namespace std;
 14 
 15 char* ReverseSentence(char *pData) {
 16     if (pData == NULL)
 17         return NULL;
 18 
 19     char *pBegin = pData;
 20 
 21     char *pEnd = pData;
 22     while (*pEnd != '\0')
 23         pEnd++;
 24     pEnd--;
 25 
 26     // 翻转整个句子
 27     Reverse(pBegin, pEnd);
 28 
 29     // 翻转句子中的每个单词
 30     pBegin = pEnd = pData;
 31     while (*pBegin != '\0') {
 32         if (*pBegin == ' ') {
 33             pBegin++;
 34             pEnd++;
 35         } else if (*pEnd == ' ' || *pEnd == '\0') {
 36             Reverse(pBegin, --pEnd);
 37             pBegin = ++pEnd;
 38         } else {
 39             pEnd++;
 40         }
 41     }
 42 
 43     return pData;
 44 }
 45 
 46 // ====================测试代码====================
 47 void Test(char* testName, char* input, char* expectedResult) {
 48     if (testName != NULL)
 49         printf("%s begins: ", testName);
 50 
 51     ReverseSentence(input);
 52 
 53     if ((input == NULL && expectedResult == NULL)
 54             || (input != NULL && strcmp(input, expectedResult) == 0))
 55         printf("Passed.\n\n");
 56     else
 57         printf("Failed.\n\n");
 58 }
 59 
 60 // 功能测试,句子中有多个单词
 61 void Test1() {
 62     char input[] = "I am a student.";
 63     char expected[] = "student. a am I";
 64 
 65     Test("Test1", input, expected);
 66 }
 67 
 68 // 功能测试,句子中只有一个单词
 69 void Test2() {
 70     char input[] = "Wonderful";
 71     char expected[] = "Wonderful";
 72 
 73     Test("Test2", input, expected);
 74 }
 75 
 76 // 鲁棒性测试
 77 void Test3() {
 78     Test("Test3", NULL, NULL);
 79 }
 80 
 81 // 边界值测试,测试空字符串
 82 void Test4() {
 83     Test("Test4", "", "");
 84 }
 85 
 86 // 边界值测试,字符串中只有空格
 87 void Test5() {
 88     char input[] = "   ";
 89     char expected[] = "   ";
 90     Test("Test5", input, expected);
 91 }
 92 
 93 int main(int argc, char** argv) {
 94     Test1();
 95     Test2();
 96     Test3();
 97     Test4();
 98     Test5();
 99 
100     return 0;
101 }

 

posted @ 2016-06-24 19:53  回看欧洲  阅读(142)  评论(0编辑  收藏  举报