
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
Check If Two Strings Are 0 or 1 Edit Distance Away in Python
Suppose we have two strings S and T we have to check whether they are one or zero edit distance away or not. An edit operation can be defined as deleting a character, adding a character, or replacing a character with another character.
So, if the input is like S = "hello", T = "hallo", then the output will be True, as these two strings have edit distance of 1.
To solve this, we will follow these steps −
- m := size of S, n := size of T
- i := 0, j := 0
- count := 0
- if |m - n| > 1, then
- return False
- while i < m and j < n, do
- if S[i] is not same as T[j], then
- if count is same as 1, then
- return False
- if m < n, then
- j := j + 1
- otherwise when m > n, then
- i := i + 1
- otherwise,
- i := i + 1, j := j + 1
- count := count + 1
- if count is same as 1, then
- otherwise,
- i := i + 1, j := j + 1
- if S[i] is not same as T[j], then
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, S, T): m, n = len(S), len(T) i, j = 0, 0 count = 0 if abs(m - n) > 1: return False while i < m and j < n: if S[i] != T[j]: if count == 1: return False if m < n: j += 1 elif m > n: i += 1 else: i += 1 j += 1 count += 1 else: i += 1 j += 1 return True ob = Solution() S = "hello" T = "hallo" print(ob.solve(S, T))
Input
"hello", "hallo"
Output
True
Advertisements