Moves in squared strings (II)(C语言CodeWars)

27 篇文章 2 订阅

解题思路:

(1)利用之前的函数,实现反转,原来还有函数strrev(),我好笨呀

(2)将其拆分为两部分,分别处理,最后再拼接起来

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* horMirror(char* strng) {
    int tlen = strlen(strng),cols,begin,end;
    char *str = strdup(strng),*token = strtok(strng,"\n");
    cols = strlen(token),begin = 0,end = cols;
    while(token!=NULL) {
        for(int i=begin;i<end;i++) str[(tlen-cols)-begin+(i-begin)]=strng[i];
	begin = end+1,end = end+1+cols;
	token = strtok(NULL,"\n");
    }
    return str;
}
 
char* vertMirror(char* strng) {
    int tlen = strlen(strng),cols,begin,end;
    char *str = strdup(strng),*token = strtok(strng,"\n");
    cols = strlen(token),begin = 0,end = cols;
    while(token!=NULL) {
	for(int i=begin;i<end;i++) str[end-(i-begin+1)]=strng[i];
	begin = end+1,end = end+1+cols;
	token = strtok(NULL,"\n");
    }
    return str;
}

char *rot(char* strng) {
    return horMirror(vertMirror(strng));
}

char* selfieAndRot(char* strng) {
    int tlen = strlen(strng),cols,rows,begin,middle,end;
    char *str = strdup(strng),*token = strtok(strng,"\n");
    cols = strlen(token),rows = (tlen+1)/(cols+1);
    char *str1 = (char*)calloc((2*cols+1)*rows+1,sizeof(char));
    for(int i=0;i<rows;i++) {
	begin = (2*cols+1)*i,end = (2*cols+1)*(i+1);
	middle = begin+cols;
	//printf("%d %d %d\n",begin,middle,end);
	for(int j=begin;j<middle;j++) str1[j]=str[j-i*cols];
	for(int j=middle;j<end-1;j++) str1[j]='.';
	str1[end-1]='\n';
    }
	
    str = rot(str);
	
    char *str2 = (char*)calloc((2*cols+1)*rows,sizeof(char));
    for(int i=0;i<rows;i++) {
	begin = (2*cols+1)*i,end = (2*cols+1)*(i+1);
	middle = begin+cols;
	for(int j=begin;j<middle;j++) str2[j]='.';
		
	for(int j=middle;j<end-1;j++) str2[j]=str[j-(i+1)*cols];
	if(i<rows-1) str2[end-1]='\n';
    }
	
    char *total = (char*)calloc((2*cols+1)*2*rows,sizeof(char));
    strcat(total,str1);strcat(total,str2);
    free(str),str1=NULL;free(str1),str1=NULL;
    free(str2),str2=NULL;token = NULL;
    return total;
}

typedef char* (*generic_func_t) (char*);
char* oper(generic_func_t f, char* s) {
    return f(s);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值