example: ab**cd**e*12
处理后结果为:*****abcde12,函数返回值5
这个题目类似于上一个题,即使用快慢指针解决。本以为不难,但是还是有点区别,因为这道题的快慢指针的初始化是在串的最后一个字符,然后往前移,而终止条件是第一个字符,上一道题的终止条件是最后一个字符的下一个字符。
- /*
- * Copyright (c) 2011 alexingcool. All Rights Reserved.
- */
- #include <iostream>
- #define NUMBER 1000
- using namespace std;
- char source[] = "ab**cd**e*12";
- const int size = sizeof source / sizeof *source;
- int moveStar(char *array, int size)
- {
- char *fast = array + size - 1, *slow = array + size - 1;
- int num;
- while(fast != array) {
- if(*fast != '*') {
- *slow = *fast;
- slow--;
- }
- fast--;
- }
- *slow-- = *fast;
- num = slow - array + 1;
- while(slow != array)
- *slow-- = '*';
- *slow = '*';
- return num;
- }
- void main()
- {
- int starNumber = moveStar(source, size);
- cout << "source = " << source << endl;
- cout << "starNumber = " << starNumber << endl;
- }
结果如下:
上面的代码有个bug,总体思路是对的,当输入为*ab**cd**e*12时,出现错误,需要做一个小改动
- int moveStar(char *array, int size)
- {
- char *fast = array + size - 1, *slow = array + size - 1;
- int num;
- while(fast != array - 1) {
- if(*fast != '*') {
- *slow = *fast;
- slow--;
- }
- fast--;
- }
- num = slow - array + 1;
- while(slow != array)
- *slow-- = '*';
- *slow = '*';
- return num;
- }
结果: