Leetcode刷题笔记6:ZigZag Conversion(C语言)

欢迎关注博主的公众号:happyGirl的异想世界。有更多干货还有技术讨论群哦~

char* convert(char* s, int numRows) {
    char str[numRows+1][1000];
    int i=0,j=0,n,p=0,flag=0;//p记录现在填充到s的第几个字符了
    n=strlen(s);
    char *str2;
    str2=(char *)malloc((n+1)*sizeof(char));
    while(p<n)
    {
        if(numRows>1)flag=flag%(numRows-1);
        else flag=0;
        j++;//一列一列填入数字
       if(flag==0)//“之”的首末要全部填上
       {
           if(n-p>=numRows)//剩余的字符可以填满
           {
               for(i=1;i<=numRows;i++)
                   str[i][j]=s[p++];
           }
           else
           {
               int q=n-p+1;
               for(i=1;i<=q;i++)
                   str[i][j]=s[p++];
               for(i=q;i<=numRows;i++)
               {
                   str[i][j]=' ';
               }
           }
       }
        else//每一列只需要填一个字符
        {
            for(i=1;i<=numRows;i++)
            {
                if(i==(numRows-flag))
                {
                    str[i][j]=s[p++];
                }
                else
                {
                	str[i][j]=' ';
                } 
            }
        }
        flag++;
    }
    n=j;//共j列
    p=0;
    for(i=1;i<=numRows;i++)
    {
        for(j=1;j<=n;j++)
        {
             if(str[i][j]!=' ')
            {
                str2[p]=str[i][j];p++;
            }
        }
    }
    str2[p]='\0';
    return str2;
}

更优的sample:

char* convert(char* s, int numRows) {
	if (numRows == 1) return s;
	else if (numRows == 0) return NULL;

    int len = strlen(s);
    int i;
    int ind[10000];
    char ret[10000] = {0};
    //int *ind = (int*)malloc(sizeof(int) * len);
    //char *ret = (char*)malloc(sizeof(char) * (len+1));
    int mod = numRows*2-2;

    int index = 0;
    for (i = 0;i < numRows;i++){
    	int count = i;
    	if (i != 0 && i != numRows-1){
    		while(count<len){
    			ind[count] = index++;
    			count = count + mod - i - i;
    			if (count >= len) break;
    			ind[count] = index++;
    			count = count + i + i;    			
    		}
    	}
    	else {
    		while(count<len){
    			ind[count] = index++;
    			count += mod;
    		}
    	}
    }

    for (i = 0;i<len;i++){
    	ret[ind[i]] = s[i];
    }
    strcpy(s, ret);
    //free(ret);
    //free(ind);
    return s;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值