Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

有序队列 #148

Open
yankewei opened this issue Aug 3, 2022 · 1 comment
Open

有序队列 #148

yankewei opened this issue Aug 3, 2022 · 1 comment
Labels
困难 题目难度为困难 字符串 题目类型为字符串 排序 题目包含排序解法

Comments

@yankewei
Copy link
Owner

yankewei commented Aug 3, 2022

给定一个字符串 s 和一个整数 k 。你可以从 s 的前 k 个字母中选择一个,并把它加到字符串的末尾。

返回 在应用上述步骤的任意数量的移动后,字典上最小的字符串 。

示例 1:

输入:s = "cba", k = 1
输出:"acb"
解释:
在第一步中,我们将第一个字符(“c”)移动到最后,获得字符串 “bac”。
在第二步中,我们将第一个字符(“b”)移动到最后,获得最终结果 “acb”。

示例 2:

输入:s = "baaca", k = 3
输出:"aaabc"
解释:
在第一步中,我们将第一个字符(“b”)移动到最后,获得字符串 “aacab”。
在第二步中,我们将第三个字符(“c”)移动到最后,获得最终结果 “aaabc”。

提示:

  • 1 <= k <= S.length <= 1000
  • s 只由小写字母组成。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/orderly-queue
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 困难 题目难度为困难 字符串 题目类型为字符串 排序 题目包含排序解法 labels Aug 3, 2022
@yankewei
Copy link
Owner Author

yankewei commented Aug 3, 2022

题目看似是一个困难题,但分析之后会发现很简单
对 key 的值分情况讨论

  • 当 key=1 时,也就是移动 n-1 次,n 为字符串长度,就可以把所有可能的值全部列出来,对比所以的字符串找到最小的即可。
  • 当 key>1 时,其实我们可以通过移动有限的次数找到一个升序的字符串,所以针对这种情况我们只需对字符串排序即可。
class Solution {

    /**
     * @param String $s
     * @param Integer $k
     * @return String
     */
    function orderlyQueue($s, $k) {
        if ($k > 1) {
            $arr = str_split($s, 1); // 不能使用 explode 函数,因为 explode 的第一个参数不能时空
            sort($arr);
            return implode('', $arr);
        }

        $result = $s;
        for ($i = 0; $i < strlen($s); $i++) {
            $s = substr($s, 1) . $s[0];
            if (strcasecmp($s, $result) < 0) {
                $result = $s;
            }
        }

        return $result;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
困难 题目难度为困难 字符串 题目类型为字符串 排序 题目包含排序解法
Projects
None yet
Development

No branches or pull requests

1 participant