Suppose we have two strings p and q, and also have a number r, we have to check whether p can be converted to q by shifting some characters clockwise at most r times. So, as an example, "c" can be turned into "e" using 2 clockwise shifts.
So, if the input is like p = "abc", q = "ccc", r = 3, then the output will be True, as we can make "a" into "c" by using 2 clockwise shifts and then convert "b" into "c" by using 1 clockwise shift, for a total of 3 shifts.
To solve this, we will follow these steps −
- if size of a is not same as size of b, then
- return False
- if k is same as 0 and a is not same as b, then
- return False
- su:= 0
- for i in range 0 to size of a, do
- v := ASCII of b[i] - ASCII of a[i]
- if v>=0, then
- su := su + v
- otherwise,
- su := su + v + 26
- if su > k, then
- return False
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, a, b, k): if len(a) != len(b): return False if k == 0 and a != b: return False su=0 for i in range(len(a)): v = ord(b[i])- ord(a[i]) if v>=0: su+=v else: su+=v+26 if su>k: return False return True ob = Solution() print(ob.solve("abc", "ccc", 3))
Input
"abc", "ccc", 3
Output
True