[LeetCode] Find Permutation 找全排列

本文介绍了一种根据由D和I字符组成的秘密签名生成对应数字字符串的方法。利用贪婪算法找到符合给定升序和降序关系的最小字典序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decreasing relationship between two numbers, 'I' represents an increasing relationship between two numbers. And our secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n (n is the length of the secret signature plus 1). For example, the secret signature "DI" can be constructed by array [2,1,3] or [3,1,2], but won't be constructed by array [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can't represent the "DI" secret signature.

On the other hand, now your job is to find the lexicographically smallest permutation of [1, 2, ... n] could refer to the given secret signature in the input.

Example 1:

Input: "I"
Output: [1,2]
Explanation: [1,2] is the only legal initial spectial string can construct secret signature "I", where the number 1 and 2 construct an increasing relationship.

 

Example 2:

Input: "DI"
Output: [2,1,3]
Explanation: Both [2,1,3] and [3,1,2] can construct the secret signature "DI", 
but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3]

 

Note:

  • The input string will only contain the character 'D' and 'I'.
  • The length of input string is a positive integer and will not exceed 10,000

 

这道题给了我们一个由D和I两个字符组成的字符串,分别表示对应位置的升序和降序,要我们根据这个字符串生成对应的数字字符串。由于受名字中的permutation的影响,感觉做法应该是找出所有的全排列然后逐个数字验证,这种方法十有八九无法通过OJ。其实这题用贪婪算法最为简单,我们来看一个例子:

D D I I D I

1 2 3 4 5 6 7

3 2 1 4 6 5 7

我们不难看出,只有D对应的位置附近的数字才需要变换,而且变换方法就是倒置一下字符串,我们要做的就是通过D的位置来确定需要倒置的子字符串的起始位置和长度即可。通过观察,我们需要记录D的起始位置i,还有D的连续个数k,那么我们只需要在数组中倒置[i, i+k]之间的数字即可,根据上述思路可以写出代码如下:

 

解法一:

class Solution {
public:
    vector<int> findPermutation(string s) {
        int n = s.size(), cnt = 0;
        vector<int> res(n + 1);
        for (int i = 0; i < n + 1; ++i) res[i] = i + 1;
        for (int i = 0; i < n; ++i) {
            if (s[i] == 'D') {
                int j = i;
                while (s[i] == 'D' && i < n) ++i;
                reverse(res.begin() + j, res.begin() + i + 1);
                --i;
            } else {
                cnt = 0;
            }
        }
        return res;
    }
};

 

下面这种方法没有用到数组倒置,而是根据情况来往结果res中加入正确顺序的数字,我们遍历s字符串,遇到D直接跳过,遇到I进行处理,我们每次先记录下结果res的长度size,然后从i+1的位置开始往size遍历,将数字加入结果res中即可,参见代码如下:

 

解法二:

class Solution {
public:
    vector<int> findPermutation(string s) {
        vector<int> res;
        for (int i = 0; i < s.size() + 1; ++i) {
            if (i == s.size() || s[i] == 'I') {
                int size = res.size();
                for (int j = i + 1; j > size; --j) {
                    res.push_back(j);
                }
            }
        }
        return res;
    }
};

 

类似题目:

Palindrome Permutation II

Palindrome Permutation

Permutation Sequence

Permutations II

Permutations

Next Permutation

 

参考资料:

https://discuss.leetcode.com/topic/76230/c-simple-solution-in-72ms-and-9-lines/2

https://discuss.leetcode.com/topic/76213/greedy-o-n-java-solution-with-explanation

https://discuss.leetcode.com/topic/76221/java-o-n-clean-solution-easy-to-understand/2

 

LeetCode All in One 题目讲解汇总(持续更新中...)

全排列是指将一个字符串中的字符进行重新排列,使得所有可能的排列都被考虑到。对于给定的字符串s,可以使用递归的方法来实现全排列。首先,选择一个字符作为排列的第一个字符,然后对剩余的字符进行全排列。这个过程可以通过不断交换字符的位置来实现。具体的代码实现可以参考以下示例代码: ```java public class StringPermutation { public void permutation(String s) { char\[\] array = s.toCharArray(); permutationHelper(array, 0, array.length - 1); } private void permutationHelper(char\[\] array, int start, int end) { if (start >= end) { System.out.println(new String(array)); } else { for (int i = start; i <= end; i++) { swap(array, i, start); permutationHelper(array, start + 1, end); swap(array, i, start); } } } private void swap(char\[\] array, int i, int j) { char temp = array\[i\]; array\[i\] = array\[j\]; array\[j\] = temp; } public static void main(String\[\] args) { StringPermutation permutation = new StringPermutation(); String s = "abc"; permutation.permutation(s); } } ``` 这段代码会输出字符串"abc"的所有全排列,即"abc"、"acb"、"bac"、"bca"、"cab"、"cba"。\[2\] 需要注意的是,全排列的时间复杂度为O(n!),其中n为字符串的长度。因此,对于较长的字符串,全排列可能会非常耗时。如果只需要判断一个字符串是否是另一个字符串的排列,可以使用类似于438. Find All Anagrams in a String的方法,只需要比较两个字符串中长度相同的子字符串所包含的字符是否一样即可。\[1\] #### 引用[.reference_title] - *1* [[LeetCode] 567. Permutation in String 字符串中的全排列](https://blog.youkuaiyun.com/weixin_30802171/article/details/97515238)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [字符串全排列问题](https://blog.youkuaiyun.com/weixin_41876155/article/details/81869743)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值