leetcode68. 文本左右对齐
思路
- 按照题目的意思来
- 计算长度时,每一行的字符长度之和不能超过最大值,两个单词之间至少有一个空格,分为中间单词和最后一个单词。
- 填充时,分为最后一排左对齐和非最后一排散列对齐
- 其中非最后一排还分为一个单词和多个单词处理的过程,一个单词,直接填充就完事了
最后一排的最后一个单词后面需要将多的位置用空格补齐
代码include
include
include
char fullJustify(char words, int wordsSize, int maxWidth, int* returnSize){
int i=0;
char **res = (char**)malloc(sizeof(char*)*wordsSize);
int count = 0;
* returnSize=0;
int starti=0,endi=0;
while(i<wordsSize) {
while(i<wordsSize&&(count+strlen(words[i])+1<=maxWidth||count+strlen(words[i])==maxWidth)) {
if(count==0)
starti = i;
if(count+strlen(words[i])+1<=maxWidth)//中间单词
count = count + strlen(words[i])+1;
else if(count+strlen(words[i])==maxWidth)//最后一个单词
count=count+strlen(words[i]);
i++;//注意弹出while循环的i是破坏表达式的i,使用时需要i-1;
}
{
if(i!=wordsSize){ //非最后一行
char *re = malloc(sizeof(char)*(maxWidth*2));
re[0] = '\0';
endi = i-1;
count = 0;
int wordcount = endi -starti +1;
int blockcount = wordcount - 1;
if(blockcount==0){ //一个单词左对齐
strcat(re,words[starti]);
for(int j = 0;j<maxWidth - strlen(words[starti]);j++) {
strcat(re," ");
}
}
else { //多个单词
int allcount = 0;
for(int j = starti;j<=endi;j++){
allcount = allcount+strlen(words[j]);
}
int block = (maxWidth-allcount)/blockcount;//平均空格数
int outblock = (maxWidth-allcount)%blockcount;//多出来的空格数
for(int j = starti;j<=endi;j++){
if(j!=endi){
//printf("words[j] = %s\n",words[j]);
strcat(re,words[j]);
for(int k = 0;k<block;k++){
strcat(re," ");
}
if(outblock!=0){
strcat(re," ");
outblock--;
}
}
else {
strcat(re,words[j]);
}
}
}
res[(*returnSize)] = re;
}
else { //最后一排
char *re = malloc(sizeof(char)*(maxWidth*2));
re[0] = '\0';
endi = i-1;
int outblock = maxWidth;
for(int j = starti;j<=endi;j++){
if(j!=endi){ //中间左对齐
strcat(re,words[j]);
strcat(re," ");
outblock = outblock -strlen(words[j]) -1;
}
else {
strcat(re,words[j]);
outblock = outblock -strlen(words[j]);
for(int k = 0;k<outblock;k++){ //如果空位没用完还是需要补齐
strcat(re," ");
}
}
}
res[(*returnSize)] = re;
}
(*returnSize)++;
count = 0;
}
}
return res;
}
// void test(char **word) {
// printf(“%s\n”,word[0]);
// printf(“%s\n”,word[1]);
// }int main() {
char *word[7]={ "This", "is", "an", "example", "of", "text", "justification."};
int maxwidth = 16;
int wordssize = 7;
int returnsize = 0;
char **re = fullJustify(word,wordssize,maxwidth,&returnsize);
printf("returnsize= %d\n",returnsize);
for(int i =0;i<returnsize;i++){
printf("%s\n",re[i]);
}
printf("%d\n",strlen(re[returnsize-1]));
// char words[15] = "this";
// strcpy(words,' ');
// strcpy(words,"test");
// printf("%s\n",words);
}
还没有评论,来说两句吧...