

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find minimum number of monotonous string groups in Python
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
- Related Questions & Answers
- Program to find minimum number of groups in communication towers in C++?
- Program to find how many updates required to make string half monotonous in Python
- Program to find minimum number of operations to make string sorted in Python
- Program to find maximum number of balanced groups of parentheses in Python
- Program to find maximum number of groups getting fresh donuts in Python
- Program to find minimum number of people to teach in Python
- Program to find number of friend groups in a set of friends connections in Python
- Program to find minimum number of operations required to make one string substring of other in Python
- Python Program for Find minimum sum of factors of number
- Program to find minimum number of rocketships needed for rescue in Python
- Program to find number of minimum steps to reach last index in Python
- Program to find minimum number of days to eat N oranges in Python
- Program to find minimum deletions to make string balanced in Python
- Program to find minimum number of operations required to make one number to another in Python
- Program to check minimum number of characters needed to make string palindrome in Python