Given two strings s
and t
, your goal is to convert s
into t
in k
moves or less.
During the ith
(1 <= i <= k
) move you can:
- Choose any index
j
(1-indexed) froms
, such that1 <= j <= s.length
andj
has not been chosen in any previous move, and shift the character at that indexi
times. - Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z'
becomes 'a'
). Shifting a character by i
means applying the shift operations i
times.
Remember that any index j
can be picked at most once.
Return true
if it’s possible to convert s
into t
in no more than k
moves, otherwise return false
.
Example 1:
Input: s = "input", t = "ouput", k = 9 Output: true Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
Example 2:
Input: s = "abc", t = "bcd", k = 10 Output: false Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
Example 3:
Input: s = "aab", t = "bbb", k = 27 Output: true Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
Constraints:
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s
,t
contain only lowercase English letters.
Solution: HashTable
Count how many times a d-shift has occurred.
a -> c is a 2-shift, z -> b is also 2-shift
a -> d is a 3-shift
a -> a is a 0-shift that we can skip
if a d-shift happened for the first time, we need at least d moves
However, if it happened for c times, we need at least d + 26 * c moves
e.g. we can do a 2-shift at the 2nd move, do another one at 2 + 26 = 28th move and do another at 2 + 26*2 = 54th move, and so on.
Need to find maximum move we need and make sure that one is <= k.
Since we can pick any index to shift, so the order doesn’t matter. We can start from left to right.
Time complexity: O(n)
Space complexity: O(26) = O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua class Solution { public: bool canConvertString(string s, string t, int k) { if (s.length() != t.length()) return false; vector<int> count(26); for (int i = 0; i < s.length(); ++i) { int d = (t[i] - s[i] + 26) % 26; int c = count[d]++; if (d != 0 && d + c * 26 > k) return false; } return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment