
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Length of Longest Consecutively Increasing Substring in Python
Suppose we have a lowercase string s. This contains English letters as well as "?" Symbol. For each "?" we must either remove it or replace it with any lowercase letter. We have to find the length of the longest consecutively increasing substring that starts with letter "a".
So, if the input is like s = "vta???defke", then the output will be 6, as we can turn s into "vtabcdefke" and "abcdef" is the longest consecutively increasing substring, and this is also starting with "a".
To solve this, we will follow these steps −
- maxlen := 0
- length := 0
- qmarks := 0
- for each c in s, do
- if c is same as "?", then
- qmarks := qmarks + 1
- otherwise,
- idx := (ASCII of c) - (ASCII of "a")
- length := idx + 1 if length <= idx <= length + qmarks or idx <= qmarks otherwise 0
- qmarks := 0
- maxlen := maximum of maxlen and (minimum of length + qmarks and 26)
- if c is same as "?", then
- return maxlen
Example
Let us see the following implementation to get better understanding −
def solve(s): maxlen = length = qmarks = 0 for c in s: if c == "?": qmarks += 1 else: idx = ord(c) - ord("a") length = idx + 1 if length <= idx <= length + qmarks or idx <= qmarks else 0 qmarks = 0 maxlen = max(maxlen, min(length + qmarks, 26)) return maxlen s = "vta???defke" print(solve(s))
Input
"vta???defke"
Output
6
Advertisements