LeetCode每日一题(1540. Can Convert String in K Moves)

发布于:2022-11-03 ⋅ 阅读:(450) ⋅ 点赞:(0)

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’.

Constraints:

  • 1 <= s.length, t.length <= 10^5
  • 0 <= k <= 10^9
  • s, t contain only lowercase English letters.

差点被这题给玩死, 上来首先想到, 我们要把 s 和 t 的差值都计算出来, 如果 t[i] >= s[i]则正常 t[i] - s[i], 如果 t[i] < s[i]我们需要绕一圈即 t[i] + 26 - s[i], 计算完之后我们首先想到排序, 我们将差值从小到大排列, 然后一个一个的进行 shift 操作, 如果该差值已经操作过了, 那我们需要将该差值+26 再进行 shift, 理论上这样可行, 但是提交的结果是超时。重新整理思路, 想到其实我们的差值一定是 0-25 之间的, 我们只需要对这些差值进行计数, 然后检查有没有(num_of_diff - 1) * 26 + diff > k 的情况, 如果有这种情况则说明没法完成。


impl Solution {
    pub fn can_convert_string(s: String, t: String, k: i32) -> bool {
        if s.len() != t.len() {
            return false;
        }
        let mut diffs = vec![0i32; 26];
        for (c1, c2) in s.chars().zip(t.chars()) {
            let c1 = c1 as u8;
            let c2 = c2 as u8;
            if c2 < c1 {
                diffs[(c2 + 26 - c1) as usize] += 1;
                continue;
            }
            diffs[(c2 - c1) as usize] += 1;
        }
        for (i, d) in diffs.into_iter().enumerate().skip(1) {
            if d > 0 && (d - 1) * 26 + i as i32 > k {
                return false;
            }
        }
        true
    }
}
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到