剑指offer第四十二题-拓展:左旋转字符串:左旋转操作是把字符串前面的若干个字符转移到字符串的尾部,如输入"abcdefg"和数字2,左旋转2位后为:"cdefgab"
1 //============================================================================ 2 // Name : JZ-C-42-Plus.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description : 左旋转字符串:左旋转操作是把字符串前面的若干个字符转移到字符串的尾部,如输入"abcdefg"和数字2,左旋转2位后为:"cdefgab" 7 //============================================================================ 8 9 #include <iostream> 10 #include <stdio.h> 11 #include "StringUtil.h" 12 #include <string.h> 13 using namespace std; 14 15 char* LeftRotateString(char* pStr, int n) { 16 if (pStr != NULL) { 17 int nLength = static_cast<int>(strlen(pStr)); 18 if (nLength > 0 && n > 0 && n < nLength) { 19 char* pFirstStart = pStr; 20 char* pFirstEnd = pStr + n - 1; 21 char* pSecondStart = pStr + n; 22 char* pSecondEnd = pStr + nLength - 1; 23 // 翻转字符串的前面n个字符 24 Reverse(pFirstStart, pFirstEnd); 25 // 翻转字符串的后面部分 26 Reverse(pSecondStart, pSecondEnd); 27 // 翻转整个字符串 28 Reverse(pFirstStart, pSecondEnd); 29 } 30 } 31 32 return pStr; 33 } 34 35 // ====================测试代码==================== 36 void Test(char* testName, char* input, int num, char* expectedResult) { 37 if (testName != NULL) 38 printf("%s begins: ", testName); 39 40 char* result = LeftRotateString(input, num); 41 42 if ((input == NULL && expectedResult == NULL) 43 || (input != NULL && strcmp(result, expectedResult) == 0)) 44 printf("Passed.\n\n"); 45 else 46 printf("Failed.\n\n"); 47 } 48 49 // 功能测试 50 void Test1() { 51 char input[] = "abcdefg"; 52 char expected[] = "cdefgab"; 53 54 Test("Test1", input, 2, expected); 55 } 56 57 // 边界值测试 58 void Test2() { 59 char input[] = "abcdefg"; 60 char expected[] = "bcdefga"; 61 62 Test("Test2", input, 1, expected); 63 } 64 65 // 边界值测试 66 void Test3() { 67 char input[] = "abcdefg"; 68 char expected[] = "gabcdef"; 69 70 Test("Test3", input, 6, expected); 71 } 72 73 // 鲁棒性测试 74 void Test4() { 75 Test("Test4", NULL, 6, NULL); 76 } 77 78 // 鲁棒性测试 79 void Test5() { 80 char input[] = "abcdefg"; 81 char expected[] = "abcdefg"; 82 83 Test("Test5", input, 0, expected); 84 } 85 86 // 鲁棒性测试 87 void Test6() { 88 char input[] = "abcdefg"; 89 char expected[] = "abcdefg"; 90 91 Test("Test6", input, 7, expected); 92 } 93 94 int main(int argc, char** argv) { 95 Test1(); 96 Test2(); 97 Test3(); 98 Test4(); 99 Test5(); 100 Test6(); 101 102 return 0; 103 }
时间: 2024-10-29 20:01:36