2022年11月17日 星期四

[1324] Print Words Vertically

陷阱很多的題目!
不能只是單純的算出row跟column 然後暴力malloc 就好了
每行row 的最後面空白還要拿掉!!!
雖然應該有機會在一個回圈裡面做完, 
但現在有點腦死XD 先貼個全部做完以後, 再每行把尾巴空白拿掉的版本
另外pointer to pointer 雙層array, 如果每行row 是指去一個 char array 的話
都要多一個字元存\0 , 慎之!!!
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** printVertically(char * s, int* returnSize){
//column=space+1
//row= max len of chacter (this is apple -> max len = 5 (apple))
char* saveS= malloc (sizeof(char)*(strlen(s)+1));
memcpy(saveS,s, strlen(s));
saveS[strlen(s)]='\0';
char* pch;
int column=0, row=0;
int removeLast=0;
int start=saveS;
pch = strtok(saveS," ");

while (pch != NULL)
{
removeLast+= (int)(pch - start);
if ((int)(pch - start) > row)
row = (pch - start)-1;
start = pch;
column++;
pch = strtok (NULL, " ");
}
//check whether last one is longest
if (strlen(s)-removeLast > row)
row = strlen(s)-removeLast;
printf("row %d , column %d\n", row, column);
char** output = malloc(sizeof (char *)* (row*column));
for (int i=0;i<row;i++)
{
output[i]= malloc (sizeof(char)* (column+1));
memset(output[i],' ', sizeof(char)* column);
output[i][column]='\0';
}
int ri=0,ci=0;
for (int idx=0; idx < strlen(s);idx++)
{
if (s[idx]!= ' ')
output[ri++][ci]=s[idx];
else
{
ri=0;
ci++;
}
}
for (int i=0;i<row;i++)
for (int check = column-1; check >0; check --)
{
if (output[i][check]==' ')
output[i][check]='\0';
else break;
}

*returnSize = row;
return output;
}


沒有留言:

張貼留言