Python程序:查找单调字符串组的最小数量
假设我们有一个小写字符串s。我们需要找到将s划分为多个连续子串的最小数量,使得每个子串要么是非递减的,要么是非递增的。例如,“pqqqr”是非递减字符串,“qqqp”是非递增字符串。
例如,如果输入是s = "pqrsrqp",则输出为2,因为我们可以将s分解为"pqrs"和"rqp"。
为了解决这个问题,我们将遵循以下步骤:
如果s为空,则
返回0
last := s[0]
direction := 1
count := 1
对于s中的每个字符,执行:
如果char > last,则
如果direction等于1,则
direction := 0
否则,如果direction等于2,则
direction := 1
count := count + 1
否则,如果char < last,则
如果direction等于1,则
direction := 2
否则,如果direction等于0,则
direction := 1
count := count + 1
last := char
返回count
示例
让我们看下面的实现来更好地理解
def solve(s): if not s: return 0 last = s[0] direction = 1 count = 1 for char in s: if char > last: if direction == 1: direction = 0 elif direction == 2: direction = 1 count += 1 elif char < last: if direction == 1: direction = 2 elif direction == 0: direction = 1 count += 1 last = char return count s = "pqrsrqp" print(solve(s))
输入
"pqrsrqp"
输出
2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP