左旋转字符串
来源:互联网 发布:人工智能会取代人类吗 编辑:程序博客网 时间:2024/04/29 11:46
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
#include <iostream>using namespace std;void Reverse(char* pBegin, char* pEnd){if(pBegin == NULL || pEnd == NULL)return;while(pBegin < pEnd){char temp = *pBegin;*pBegin = *pEnd;*pEnd = temp;pBegin++;pEnd--;}}
char* LeftRotateString(char* str, int n){if(str != NULL){int length = strlen(str);if(length > 0 && n > 0 && length > n){char* pBegin = str;char* pStr = str + n -1;char* pEnd = str + length -1;Reverse(pBegin, pStr);Reverse(pStr+1, pEnd);Reverse(pBegin, pEnd);}}return str;}
// ====================测试代码====================void Test(char* testName, char* input, int num, char* expectedResult){ if(testName != NULL) printf("%s begins: ", testName); char* result = LeftRotateString(input, num); if((input == NULL && expectedResult == NULL) || (input != NULL && strcmp(result, expectedResult) == 0)) printf("Passed.\n\n"); else printf("Failed.\n\n");}// 功能测试void Test1(){ char input[] = "abcdefg"; char expected[] = "cdefgab"; Test("Test1", input, 2, expected);}// 边界值测试void Test2(){ char input[] = "abcdefg"; char expected[] = "bcdefga"; Test("Test2", input, 1, expected);}// 边界值测试void Test3(){ char input[] = "abcdefg"; char expected[] = "gabcdef"; Test("Test3", input, 6, expected);}// 鲁棒性测试void Test4(){ Test("Test4", NULL, 6, NULL);}// 鲁棒性测试void Test5(){ char input[] = "abcdefg"; char expected[] = "abcdefg"; Test("Test5", input, 0, expected);}// 鲁棒性测试void Test6(){ char input[] = "abcdefg"; char expected[] = "abcdefg"; Test("Test6", input, 7, expected);}int main(int argc, char* argv[]){ Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); return 0;}
0 0
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 26.左旋转字符串
- 第一章、左旋转字符串
- 字符串的左旋转
- 第一章、左旋转字符串
- 第一章、左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 26、左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 左旋转字符串
- 源泉书签,迁移至阿里云云服务器ECS,带来更好的用户体验
- 九度OJ 题目1153:括号匹配问题
- [LeetCode] Reverse Linked List II(!!!)
- static修饰的变量和函数与普通变量函数的区别
- ssh密钥认证原理
- 左旋转字符串
- ssoj1944采矿(oremine)(最长链)
- android 裁剪
- 条款18 让接口容易被正确使用,不易被误用
- Internet采用哪种网络协议?该协议的主要层次结构?
- poj-1066 Treasure Hunt
- setContentView和inflate区别
- 漫谈C指针第七讲---const int *pi 的语义
- 如何用FileItem来实现文件上传