1. 题目描述LeetCode 1324题,题目名称为“Print Words Vertically”,要求你给定一个字符串 s,按照字典序打印出给定字符串的每一列,如果某一列没有字符,则用空格填充。...
LeetCode 1324题,题目名称为“Print Words Vertically”,要求你给定一个字符串 s,按照字典序打印出给定字符串的每一列,如果某一列没有字符,则用空格填充。
为了解决这个问题,我们可以按照以下步骤进行:
下面是使用C语言实现的代码示例:
#include
#include
void printVertically(const char *s) { int len = strlen(s); int maxLen = 0; int wordCount = 0; const char *words[len + 1]; // 确定列数 for (int i = 0; i < len; ++i) { if (s[i] != ' ') { if (maxLen < i + 1) { maxLen = i + 1; } wordCount++; words[wordCount - 1] = s + i; } } // 遍历列 for (int col = 0; col < maxLen; ++col) { int printed = 0; for (int row = 0; row < wordCount; ++row) { if (col < strlen(words[row])) { printf("%c", words[row][col]); printed = 1; } else { printf(" "); } } if (!printed) { printf(" "); } printf("\n"); }
}
int main() { const char *s = "Hello World"; printVertically(s); return 0;
} 输入:Hello World输出:
H
e
l
l
o
W
o
r
l
d输入:LEETCODE输出:
L
E
E
T
C
O
D
E通过以上步骤和代码实现,我们可以成功地解决LeetCode 1324题。