Write a program that creates a class named Words
to receive an array of strings as an attribute. Then create a method to find the longest common prefix string amongst the array of strings. The following shows an execution of the method. (Hint: find the shortest word at first.)
x=Words(("flower","flow","flight"))
print(x.prefix())
#output
"fl"
----------------------------------------------------------------------------
y=Words(("apple","application","appendix","appointment"))
print(y.prefix())
#output
"app"
根据题目提示做就好了啊。
先循环一遍找到最短得单词 (避免用最长的单词浪费时间)。
然后用一个变量记到目前为止公共前缀的长度,初始为最短单词的长度。
然后用最短单词于其余单词一个个比较前缀,最多比较公共前缀的长度个字符。如果没有这么多公共前缀字符,减小公共前缀的长度变量值到该单词的公共前缀长度。
继续余下的单词。
如果到某个时候公共前缀的长度为0,就不需要继续后面的单词了。说明没有公共前缀了。
希望这个思路能帮上忙。
附注:求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载,需要20积分/C币。赞助多少都可以。多谢。