问题描述
把字符串s中的字符从左到右写入行中,每行最大宽度为100,如果往后新写入一个字符导致该行宽度超过100,则写入下一行。
其中,一个字符串的宽度有一个给定的数组widths决定,widths[0]是字符a的宽度,...,widths[25]是字符z的宽度。问:
把字符串s全部写完,至少需要多少行?最后一行用去的宽度是多少?将结果作为整数列表返回
# 假若widths符合如下list widths = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] def str_write_lines(chrs): temp = [] line_num, lines = 0, [] chr_ptr, chr_len = 0, len(chrs) while chr_ptr < chr_len: cur_chr = chrs[chr_ptr] idx = ord(cur_chr)-97 # ascii码(a)=97 temp_len = widths[idx] total = line_num+temp_len if total > 100: if temp: lines.append(temp) line_num = temp_len temp = [cur_chr] else: temp.append(cur_chr) line_num = total chr_ptr += 1 if temp: lines.append(temp) return lines muti_chars = 'xxxxxyyyyyzzzzzuuuuuvvv' lines = str_write_lines(muti_chars) print('line_num', len(lines), 'the last line_num', len(lines[-1])) for num, line in enumerate(lines): print('line:', num+1, ''.join(line))