任意输入一个字符串,串中连续出现的相同元素构成的子序列称为平台,试建立一个类Str,求出串中最长平台的长度,并能输出最长平台的子序列。如字符串为“jkkkaabbbbbaaa”,则最长平台长度为5,子序列为“bbbbb”
时间: 2024-09-12 12:11:12 浏览: 32
python字符、字符串、文本.pdf
为了实现这个功能,我们可以创建一个名为`Str`的类,该类包含两个方法:`find_longest_platform_length`用于计算最长平台的长度,以及`get_longest_platform_sequence`用于获取最长平台的子序列。下面是这个类的一个简单实现:
```python
class Str:
def __init__(self, input_string):
self.string = input_string
def find_longest_platform_length(self):
platform_length = 0
current_length = 1
previous_char = self.string[0]
for char in self.string[1:]:
if char == previous_char:
current_length += 1
else:
platform_length = max(platform_length, current_length)
current_length = 1
previous_char = char
# Check for the last platform
platform_length = max(platform_length, current_length)
return platform_length
def get_longest_platform_sequence(self):
longest_platform = ""
current_platform = self.string[0]
for char in self.string[1:]:
if char == current_platform:
current_platform += char
else:
if len(current_platform) > len(longest_platform):
longest_platform = current_platform
current_platform = char
# Check for the last platform
if len(current_platform) > len(longest_platform):
longest_platform = current_platform
return longest_platform
# 示例
input_str = "jkkkaabbbbbaaa"
str_instance = Str(input_str)
longest_length = str_instance.find_longest_platform_length()
platform_seq = str_instance.get_longest_platform_sequence()
print(f"最长平台的长度为:{longest_length}")
print(f"最长平台的子序列是:{platform_seq}")
阅读全文