Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to check typed string is for writing target string in stuck keyboard keys or not in Python
Suppose we have two strings s and t. We want to form t, but there are some problems in the keyboard where some of characters stuck so they may be written 1 or more times. We have to check whether it's possible that typed s was meant to write t or not.
So, if the input is like s = "appppleee" t = "apple", then the output will be True.
To solve this, we will follow these steps −
- i := 0, j := 0
- s_len := size of s
- t_len := size of t
- t_last := blank string
- while j < t_len, do
- if i is same as s_len, then
- return False
- if s[i] is same as t[j], then
- t_last := t[j]
- i := i + 1
- j := j + 1
- otherwise when s[i] is same as t_last, then
- i := i + 1
- otherwise,
- return False
- if i is same as s_len, then
- if i < s_len, then
- return true if all char in s[from index i to end] is same as t_last
- otherwise,
- return True
Example
Let us see the following implementation to get better understanding −
def solve(s, t): i = j = 0 s_len = len(s) t_len = len(t) t_last = "" while j < t_len: if i == s_len: return False if s[i] == t[j]: t_last = t[j] i += 1 j += 1 elif s[i] == t_last: i += 1 else: return False if i < s_len: return all(char == t_last for char in s[i:]) else: return True s = "appppleee" t = "apple" print(solve(s, t))
Input
"appppleee", "apple"
Output
True
Advertisements
