#include <iostream> #include <cstdio> #include <cstring> using namespace std; /* //解法一: //时间复杂度为:O(K * N), //空间复杂度: O(1) char * Reverse(char *pStr, int len, int size) { len = len % size;//if len > size, it will be a recyle for (int i = size-1; i >= len; i--) { char tmp = pStr[size-1]; for (int j = size-1; j >= 1; j--) { pStr[j] = pStr[j-1]; } pStr[0] = tmp; // puts(pStr); } return pStr; } */ //解法二: //设src = "1234abc", dest = "abc1234" //T = "1234", D = "abc" //则 (T^D^)^ = DT inline void Swap(char &lps, char &rps) { char tmp = lps; lps = rps; rps = tmp; } void Reverse(char *pSrc, int pos, int size) { char *pBegin = pSrc + pos, *pEnd = pSrc + size- 1; while (pBegin < pEnd) { Swap(*pBegin, *pEnd); pBegin ++; pEnd --; } puts(pSrc); } int main() { char str[] = "1234abc"; int len = strlen(str); Reverse(str, 0, 4);//反转前4个字符 Reverse(str, 4, len);//反转后三个字符 Reverse(str, 0, len);//整体反转 puts(str); return 0; }
时间: 2024-10-03 12:02:54