全部内容来自《剑指offer》。
题目一:
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字符一样处理。例如输入字符串“I am a student.”,则输出
“student. a am I”。
ANSWER:
void reverse(char *pBegin, char *pEnd) { if (pBegin == NULL || pEnd == NULL) return; while (pBegin < pEnd) { char tmp = *pBegin; *pBegin = *pEnd; *pEnd = tmp; pBegin++; pEnd--; } } char* reverseSentence(char *pDate) { if (pDate == NULL) return NULL; char *pBegin = pDate; char *pEnd = pDate; while (*pEnd != ‘\0‘) pEnd++; pEnd--; reverse(pBegin, pEnd); pBegin = pEnd = pDate; while (*pBegin != ‘\0‘) { if (*pBegin == ‘ ‘) { pBegin++; pEnd++; } else if (*pEnd == ‘ ‘ || *pEnd == ‘\0‘) { reverse(pBegin, --pEnd); pBegin = ++pEnd; } else pEnd++; } return pDate; }
题目二:
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如输入字符串“abcdefg”和数字2,该函数将返回左旋转2位得到的结果“cdefgab”。
ANSWER:
char* leftRotateString(char *pStr, int n) { if (pStr != NULL) { int nLength = static_cast<int>(strlen(pStr)); if (nLength > 0 && n > 0 && n < nLength) { char *pFirstStart = pStr; char *pFirstEnd = pFirstStart + n - 1; char *pSecondStart = pFirstStart + n; char *pSecondEnd = pStr + nLength - 1; reverse(pFirstStart, pFirstEnd); reverse(pSecondStart, pSecondEnd); reverse(pFirstStart, pSecondEnd); } } return pStr; }
LeetCode上也有对应的题目
https://leetcode.com/problems/reverse-words-in-a-string/
时间: 2024-10-05 21:05:21