【问题标题】:Algorithms question about counting lines in a paragraph关于计算段落中行数的算法问题
【发布时间】:2020-04-07 01:10:25
【问题描述】:

我在尝试找出解决此问题的有效算法时遇到了一些麻烦。给你一个长字符串 s="a bcd e f ghi j k lmn opq ghfdj ashks jahksjh jahkdaj jhakjd akjsdhka hskadjhka hkjdhak dkahsdkhsakjdhksah"

和一个最大行长整数maxLine = 6,它决定了一行中的最大字符数,需要多少行才能适应字符串

***你不能在单词中间打断字符串**** 例如:

输入:

s="a bcd e f ghi j k lmn opq ghfdj ashks", maxLine = 6

第一行: 一个 bcd

第二行: f

第三行: 吉吉

我正在尝试通过算法解决这个问题,而不是使用包

【问题讨论】:

标签: python string algorithm math


【解决方案1】:

这是一个相当有效的解决方案,它只需要一次遍历字符串。

我们跟踪下一行的开头为line_start_index,然后我们遍历每个字符并跟踪我们看到的最后一个空格line_end_index

每次我们从 line_start_index 迭代 6 个字符时,我们都知道下一行是子字符串 s[line_start_index:line_end_index]。然后我们将line_start_index设置为上一行的结尾。

line_start_index = 0
line_end_index = 0
total = 0
for i, c in enumerate(s):
    if c == ' ':
        line_end_index = i
    if i - line_start_index == 6:
        # TODO: Handle words longer than 6 chars (line_start_index == line_end_index + 1)
        print('Found line!', s[line_start_index:line_end_index])
        total += 1
        line_start_index = line_end_index + 1

# For the data you have given there will be one additional line after the loop
# this may not be correct if the last char is a space
print('Found line!', s[line_start_index:])
total += 1
print(total)

这给出了输出:

Found line! a bcd
Found line! e f
Found line! ghi j
Found line! k lmn
Found line! opq
Found line! ghfdj
Found line! ashks
7

如果单词长度超过 6 个字符,这将不起作用,但正如您所说,不需要处理此问题

【讨论】:

    【解决方案2】:

    使用正则表达式的解决方案

    >>> re.findall(r'\b.{1,6}\b', s)
    ['a bcd ', 'e f ', 'ghi j ', 'k lmn ', 'opq ', 'ghfdj ', 'ashks']
    >>> len(_)
    7
    

    【讨论】:

    • 我试图通过算法而不是包来解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2014-02-26
    • 2020-03-09
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多