1.题目要求:
给你一个字符串 s。请你按照单词在 s 中的出现顺序将它们全部竖直返回。
单词应该以字符串列表的形式返回,必要时用空格补位,但输出尾部的空格需要删除(不允许尾随空格)。
每个单词只能放在一列上,每一列中也只能有一个单词。
示例 1:
输入:s = "HOW ARE YOU"
输出:["HAY","ORO","WEU"]
解释:每个单词都应该竖直打印。
"HAY"
"ORO"
"WEU"
示例 2:
输入:s = "TO BE OR NOT TO BE"
输出:["TBONTB","OEROOE"," T"]
解释:题目允许使用空格补位,但不允许输出末尾出现空格。
"TBONTB"
"OEROOE"
" T"
示例 3:
输入:s = "CONTEST IS COMING"
输出:["CIC","OSO","N M","T I","E N","S G","T"]
2.题目代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** printVertically(char * s, int* returnSize){
//1.设置一个二维数组,存入字符串中s的单词
char** word = (char**)malloc(sizeof(char*) * 200);
for(int i = 0;i < 200;i++){
word[i] = (char*)malloc(sizeof(char) * 50);
}
for(int i = 0;i < 200;i++){
memset(word[i],'\0',sizeof(char) * 50);
}
int j = 0;
//采用strtok函数,把分离的单词存入二维数组中
char* string = strtok(s," ");
while(string != NULL){
strcpy(word[j],string);
j++;
string = strtok(NULL," ");
}
//2.再设置一个二维数组,用来存入垂直的打印的单词
//先确定新的二维数组的长度;
int max = strlen(word[0]);
for(int i = 1;i < j;i++){
if(strlen(word[i]) > max){
max = strlen(word[i]);
}
}
//设置二维数组
char** ver_word = (char**)malloc(sizeof(char*) * max);
for(int i = 0;i < max;i++){
ver_word[i] = (char*)malloc(sizeof(char) * 500);
}
for(int i = 0;i < max;i++){
memset(ver_word[i],'\0',sizeof(char) * 500);
}
int f1 = 0;
//3.开始把word数组里单词垂直放入ver_word
for(int j1 = 0;j1 < max;j1++){
char temp[500] = { 0 };
int f = 0;
for(int i1 = 0;i1 < j;i1++){
if(word[i1][j1] == '\0'){
temp[f] = ' ';
f++;
}else{
temp[f] = word[i1][j1];
f++;
}
}
strcpy(ver_word[f1],temp);
f1++;
}
//4.删除末尾0;
for(int i = 0;i < f1;i++){
char* end = ver_word[i] + strlen(ver_word[i]) - 1;
while(*end == ' '){
*end = '\0';
end--;
}
}
*returnSize = max;
return ver_word;
}