其他分享
首页 > 其他分享> > leetcode68-文本左右对齐

leetcode68-文本左右对齐

作者:互联网

文本左右对齐

先对所有字符串进行一次遍历,保证每个字符串之间有一个空格,然后对字符串分组,确定字符串的位置。
然后对每一组的字符串分配空格:遍历这一组的字符串长度,计算出剩余的空格总数,并根据空格总数分配出固有的空格和多出来的空格数量,依次添加。
注意:最后一行字符之间只能有一个空格,需要单独列出来讨论。

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        int n = words.length, arr[] = new int[n], cnt = 0, index = 0, i = 0, j = 0, len = 0;
        List<String> list = new ArrayList<>();
        for(i = 0; i < n; i++){
            if(i == 0){
                cnt += words[i].length();
                arr[i] = index;
            }
            else if(cnt + words[i].length()+1 <= maxWidth){
                cnt += words[i].length()+1;
                arr[i] = index;
            }else{
                cnt = words[i].length();
                arr[i] = ++index;
            }
        }
        i = 0;
        while(i < n){
            len = 0;
            j = i;
            while(j < n && arr[i] == arr[j]){
                len += words[j].length();
                j++;
            }
            if(i+1 == j){
                StringBuilder sb = new StringBuilder(words[i]);
                for(int k = 0; k < maxWidth-words[i].length(); k++) sb.append(" ");
                list.add(sb.toString());
            }else if(j == n){
                StringBuilder sb = new StringBuilder(words[i]);
                for(int k = i+1; k < j; k++){
                    sb.append(" ");
                    sb.append(words[k]);
                }
                while(sb.length() < maxWidth)   sb.append(" ");
                list.add(sb.toString());
            }else{
                StringBuilder sb = new StringBuilder(words[i]);
                int space = maxWidth-len, otherspace = space % (j-i-1), certainspace = space / (j-i-1);
                for(int k = i+1; k < j; k++){
                    if(otherspace > 0){
                        otherspace--;
                        sb.append(" ");
                    }
                    for(int l = 0; l < certainspace; l++)   sb.append(" ");
                    sb.append(words[k]);
                }
                list.add(sb.toString());
            }
            i = j;
        }
        return list;
    }
}

标签:cnt,int,leetcode68,空格,words,sb,字符串,对齐,文本
来源: https://www.cnblogs.com/xzh-yyds/p/16615111.html