zoukankan      html  css  js  c++  java
  • 【leetcode】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 <= kmove 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
    • st contain only lowercase English letters.

    解题思路:统计出s中每个字符转成成t中对应的字符所需要的转换次数,如果需要转换i次的字符的数量一个有v个,那么需要满足 i + (v-1)*26 > k 。

    代码如下:

    class Solution(object):
        def canConvertString(self, s, t, k):
            """
            :type s: str
            :type t: str
            :type k: int
            :rtype: bool
            """
            if len(s) != len(t):return False
            count = [0] * 27
            for (c1,c2) in zip(s,t):
                if c1 <= c2:
                    count[ord(c2) - ord(c1)] += 1
                else:
                    count[26 - (ord(c1) - ord(c2))] += 1
            for i,v in enumerate(count):
                if i > 0 and i + (v-1)*26 > k:
                    return False
    
            return True
  • 相关阅读:
    在vue中添加实时时间
    在three中使用图片作为材质,并将材质流动起来
    在three.js中创建一个小球并且小球在外部添加辉光
    自动获取linux系统的iso镜像文件
    this指向的相关问题
    vue基础-01
    svn和git的简单使用命令和步骤
    您只能在 HTML 输出中使用 document.write。如果您在文档加载后使用该方法,会覆盖整个文档
    关于toLocaleDateString的坑
    JSON的介绍与细节
  • 原文地址:https://www.cnblogs.com/seyjs/p/13667720.html
Copyright © 2011-2022 走看看