阅读 663

用js实现css的文字两端对齐效果

文字两端对齐

  • 引言: 作为前端开发,我们常常用到text-algin这个属性使文字两端对齐。今天我们使用js来实现一个文字两端对齐的效果!
  • 题目: 给定一个所有项都是长度大于0的字符串words,以及每行最大字符数target。请实现每一行两端对齐。最后一行需要采用左对齐! eg1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]
复制代码

eg2:

Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
复制代码
  • 题目分析: 因为每一行最大字符数为target,因此,每一一行中words[i]的字符长度总数之和必须小于target,且每个words[i]之间需要至少一个空格。因此假设我们第一行中有m项,各项字符总数为count,那么我们count必须小于等于target - m + 1; 通过对words数组进行循环,计算出每一行的组成项,然后在每项之间使用相应适量的空格进行链接。但是有两点需要特殊处理,1.某一行只有一项,这种情况直接在该项后面加上相应数量的空格,2.最后一行,数组项之间采用单个空格链接,剩余空格添加在最后。

  • 具体算法如下:

const fullJustify = function(words, maxWidth) {
    let str = [];               //最终返回数组
    let strArr = [];            //每一行数组项数组
    let diff = maxWidth;        //当前行数剩余字符数量
    let total = 0;              //每一行各项数组字符长度之和
    for (let item of words) {
        const len = item.length;    //当前数组项字符长度
        if (len <= diff) {      //如果当前字符数量小于diff,则存入strArr,并更新diff
            total += len;
            strArr.push(item);
            diff -= len + 1;
        } else {
            diff = maxWidth - total;    //需要添加的空格数量
            if (strArr.length <= 1) {   //处理只有一项的特殊情况
                strArr[0] += ' '.repeat(diff);
            } else {
                while (diff > 0) {  //为每一行的数组前strArr.length - 1项添加空格
                    for (let i = 0; i < strArr.length; i++) {
                        if (diff > 0 && i < strArr.length - 1) {
                            strArr[i] = strArr[i] + ' ';
                            diff -= 1;
                        }
                    }
                }
            }
            str.push(strArr.reduce((a, b) => a + b));
            strArr = [item];
            total = len;
            diff = maxWidth - len - 1;
        }
    }
    // 处理最后一行
    diff = maxWidth - total - strArr.length + 1;
    str.push(strArr.join(' ') + ' '.repeat(diff));
    return str;
};
复制代码

解题思路大致如上,当然还有很多更好的写法,整体来说上述算法在运行耗时上表现不够优秀,可以考虑以空间换时间,再次我也只是抛砖引玉!

文章分类
前端
文章标签