zoukankan      html  css  js  c++  java
  • 快慢指针____函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移

    函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中字符'*'的数量。如原始串为:ab**cd**e*12,处理后为*****abcde12,函数并返回值为5。(要求使用尽量少的时间和辅助空间



    类似快慢指针
    i j初值为length - 1 ,如果为0则顺序会产生一定的颠倒
    i指向字母,容易保证字母指针指的靠前(只要i指向字母 就跟j指向的*换位置,换位置后则i--,j-- ;i指向*号时,i-- count++)
    j指向*


    交换代码部分替换为
    array[j] = array[i];
    array[i] = '*';
    为何出错?

     

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    
    int fun(char array[])
    {
        int length = strlen(array);
        int i, j, count;
        char temp;
    
        for(i = j = length - 1, count = 0; i >= 0; )
        {
            if(array[i] != '*')
            {
                temp = array[j];
                array[j] = array[i];
                array[i] = temp;
                i--;
                j--;
            }
            else
            {
                i--;
                count++;
            }        
        }    
        return count;
    }
    
    int main()
    {
        char a1[] = "ab**cd**e*12";
    
        printf("%d\n", fun(a1));
        puts(a1);
        return 0;
    }
  • 相关阅读:
    「2019纪中集训Day20」解题报告
    PHP基础入门
    javascript
    正则表达式
    DOM 节点
    对象
    字符串
    函数
    for循环
    jQuery
  • 原文地址:https://www.cnblogs.com/wwjyt/p/3153123.html
Copyright © 2011-2022 走看看