[LeetCode] Can Convert String in K Moves

1540. Can Convert String in K Moves

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) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool canConvertString(string s, string t, int k) {
if(s.length() != t.length())
return false;
unordered_map<int, int> m;
for(int i = 0; i < s.length(); i++) {
m[(t[i] - s[i] + 26) % 26]++;
}

for(int i = 1; i < 26; i++) {
if(m[i] && (m[i] - 1)*26 + i > k)
return false;
}
return true;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool canConvertString(string s, string t, int k) {
if(s.length() != t.length())
return false;
unordered_map<int, int> m;
int diff = -1;
for(int i = 0; i < s.length() && m[diff] <= k; i++) {
diff = (t[i] - s[i] + 26) % 26;
m[diff] += m[diff] ? 26 : diff;
}
return m[diff] <= k;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/04/PS/LeetCode/can-convert-string-in-k-moves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.