翻转单词顺序 VS 左旋转字符串
输入一个英文句子,翻转句子中的单词顺序,但单词内的字符顺序不变。如“I am a student." 则输出“student. a am I"
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* ReverseSentence(char* pData) { if( pData == NULL) return NULL; char* pBegin =pData; char* pEnd = pData; while( *pEnd !='\0') pEnd++; pEnd--; Reverse(pBegin,pEnd); //翻转句子 pBegin = pEnd =pData; while( *pBegin != '\0') { if(*pBegin == ' ')//空格 { pBegin++; pEnd++; } else if( *pEnd == ' ' || *pEnd == '\0') { Reverse(pBegin,--pEnd); pBegin = ++pEnd; } else { pEnd++; } } return pData; }
字符串的左旋转操作是把字符串的前面的若干个字符转移到字符串的尾部。例如“abcdefg“左旋转2位为”cdefgab"
我们可以把字符串看成“ab","cdefg"两部分,我们先把ab 翻转 不ba,再把cdefg翻转gfedc 得到字符串bagfedc再把整个字符串翻转cdefgab
char* LeftRotateString(char* pStr, int n) { if( pStr == NULL) return NULL; int length = static_cast<int>(strlen(pStr)); if( length > 0 && n > 0 && n <length) { char* pFirstStart = pStr; char* pFirstEnd = pStr + n -1; char* pSecondStart = pStr + n; char* pSecondEnd = pStr + length -1; Reverse(pFirstStart,pFirstEnd); Reverse(pSecondStart,pSecondEnd); Reverse(pFirstStart,pSecondEnd); } return pStr; }