描述
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.
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'.
Note:
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s, t contain only lowercase English letters.
解析
根据题意,在遍历 k 的过程中,第 i (1<=i<=k) 步的时候,可以对还没有操作过的 s 中的某个字符,进行 shift i 步的运算,如果结束的时候 s 能变为 t 则返回 True 。换个思路,如果需要的步数没超过 k 则为 True。
字符串长度不相等,直接判断为 False
因为对于字母的字典顺序差值只能是 0-25 ,所以用字典 d 保存每种差值的出现情况
遍历字符串各个位置上的字符,按照字典顺序,s[i] 的 ord 为 a ,t[i] 的 ord 为 b,如果 a < b 则 d[b-a] 的值加 1 ,如果 a > b 则 d[ord('z') - a + b - ord('a') + 1] 的值加 1
如果 d 中某个 key 对应的值为2,例如 dic[1] = 2,那么第一次转动 1,第 27 (1+26) 次转动 27,就可以满足,所以只需要判断 n+26*key 是否超过限制k
解答
class Solution(object):
if len(s)!=len(t):
return False
d = {}
for i in range(26):
d[i] = 0
for i in range(len(s)):
a = ord(s[i])
b = ord(t[i])
if a == b:
continue
elif a < b:
d[ b - a] += 1
elif a > b:
d[ord('z') - a + b - ord('a') + 1] += 1
for c in d:
if (d[c]-1) * 26 + c > k:
return False
return True
运行结果
Runtime: 332 ms, faster than 88.28% of Python online submissions for Can Convert String in K Moves.
Memory Usage: 18 MB, less than 54.48% of Python online submissions for Can Convert String in K Moves.
每日格言:人生最大遗憾莫过于错误坚持和轻易放弃