给定一个字符串、一个字符串的子串,将第一个字符串反转,但保留子串的顺序不变
例如:
输入:第一个字符串: “Welcome you, my friend”
子串:“you”
输出:“dneirf ym,you emocleW”
解析
(1)扫描一遍第一个字符串,然后用stack把它反转,同时记录下子串的位置。
(2)扫描一遍把记录下来的子串再用stack反转
(3)将堆栈的字符串弹出,这样子串又恢复了原来的顺序#include
#include <cassert>
#include <stack>
using namespace std;
void reverse(const char* s1, const char* token, char* buffer)
{
stack<char> stack1;
const char* ptoken = token, *head = s1, *rear = s1;
assert(s1 && token);
while (*head != '\0')
{
while (*head != '\0' && *ptoken == *head)
{
ptoken++;
head++;
}
if (*ptoken == '\0')
{
const char* p;
for (p = head - 1; p >= rear; p--)
{
stack1.push(*p);
}
ptoken = token;
rear = head;
}
else
{
stack1.push(*rear++);
head = rear;
ptoken = token;
}
}
while (!stack1.empty())
{
*buffer++ = stack1.top();
stack1.pop();
}
*buffer = '\0';
}
int main()
{
char str[100] = "Welcome yoyou, my friend you";
char token[100] = "you";
char buffer[100];
reverse(str,token,buffer);
cout << buffer << endl;
system("pause");
return 0;
}