Suppose we have a lowercase string s. We have to find the minimum numbers of contiguous substrings in which s is divided into parts such that each substring is either non-increasing or non-decreasing. So for example, if the string is like "pqqqr" is a non-decreasing string, and "qqqp" is a non-increasing string.
So, if the input is like s = "pqrsrqp", then the output will be 2, because we can break s like "pqrs" and "rqp".
To solve this, we will follow these steps −
if s is empty, then
return 0
last := s[0]
direction := 1
count := 1
for each char in s, do
if char > last, then
if direction is same as 1, then
direction := 0
otherwise when direction is same as 2, then
direction := 1
count := count + 1
otherwise when char < last, then
if direction is same as 1, then
direction := 2
otherwise when direction is same as 0, then
direction := 1
count := count + 1
last := char
return count
Example
Let us see the following implementation to get better understanding
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))
Input
"pqrsrqp"
Output
2