输入全大写字母字符串,求字符为升序的最长字符串
时间: 2023-06-19 08:08:35 浏览: 35
好的,我来给出解答。
首先,我们需要遍历字符串,找到所有字符为升序的子串,并记录它们的起始位置和长度。接着,找到长度最大的子串并返回它。
下面是 Python 代码实现:
```python
def longest_ascending_substring(s: str) -> str:
max_len = 0
max_start = 0
curr_len = 1
start = 0
for i in range(1, len(s)):
if s[i] >= s[i-1]:
curr_len += 1
else:
if curr_len > max_len:
max_len = curr_len
max_start = start
curr_len = 1
start = i
# 处理最后一个子串
if curr_len > max_len:
max_len = curr_len
max_start = start
return s[max_start:max_start+max_len]
```
可以看到,我们维护了当前子串的起始位置 `start`、当前子串的长度 `curr_len`,以及长度最大的子串的起始位置 `max_start` 和长度 `max_len`。当遇到一个非升序的字符时,我们就将当前子串的起始位置更新为当前位置,长度重新计数。最后,我们返回最长的子串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)