LeetCode068——文本左右对齐

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82847865

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/text-justification/description/

题目描述:

知识点:字符串

思路:依次遍历数组中的每一个元素,每一层放尽可能多的字符

本题没有应用到什么算法方面的知识,根据题意写就行了,算是LeetCode中困难难度的简单题。需要注意以下几个注意点:

(1)最后一行的对齐方式是左对齐,需要特殊处理。

(2)如果一行中只有一个单词,其后需要填充空格至maxWidth长度。

(3)如果一行中有多个单词,其单词之间空格的计算可以先算平均分配每两个单词之间能分配到的空格数averageSpace,再将多余的空格数remainSpace从左到右依次填充进两个单词的间隔里。

整个实现过程我们只遍历了数组words一次,因此时间复杂度是O(n)级别的,其中n为words数组的长度。空间复杂度是O(1)。

JAVA代码:

public class Solution {

	public List<String> fullJustify(String[] words, int maxWidth) {
		List<String> list = new ArrayList<>();
		int n = words.length;
		if(n == 0) {
			return list;
		}
		//index represents which position in array words we are traversing now
		int index = 0;
		while(index < n) {
			//every String in list contains 1 word or more
			int len = words[index].length();
			int i = index + 1;
			for (; i < words.length; i++) {
				if(len + words[i].length() + 1 > maxWidth) {
					break;
				}
				len += words[i].length() + 1;
			}
			//levelLen represents how many characters that isn't space in erery String
			int levelLen = 0;
			for (int j = index; j < i; j++) {
				levelLen += words[j].length();
			}
			//numSpace represents how many space between 2 words
			int numSpace = i - index - 1;
			//string represents every String
			String string = "";
			if(i != words.length) {
				//if we haven't traversed all the words
				if(numSpace != 0) {
					//if this String has more than one word
					int[] spaces = new int[numSpace];
					int averageSpace = (maxWidth - levelLen) / numSpace;
					int remainSpace = maxWidth - levelLen - numSpace * averageSpace;
					for (int j = 0; j < numSpace; j++) {
						if(j + 1 <= remainSpace) {
							spaces[j] = 1 + averageSpace;
						}else {
							spaces[j] = averageSpace;
						}
					}
					for (int j = index, k = 0; j < i && k < numSpace;) {
						string += words[j];
						j++;
						for (int num = 0; num < spaces[k]; num++) {
							string += " ";
						}
						k++;
					}
				}
				string += words[i - 1];
				if(numSpace == 0) {
					//if this String only has one word, fill space in the remain position
					while(string.length() < maxWidth) {
						string += " ";
					}
				}
			}else {
				//if we have traversed all the words, the last String we need to put all words on the left 
				for (int j = index; j < i - 1; j++) {
					string += words[j] + " ";
				}
				string += words[i - 1];
				while(string.length() < maxWidth) {
					string += " ";
				}
			}
			list.add(string);
			index = i;
		}
		return list;
	}
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82847865
今日推荐