Google
484 Find Permutation

1. Question

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:
1
Input: "I"
2
3
Output:
4
[1,2]
5
6
Explanation:
7
[1,2] is the only legal initial spectial string can construct secret signature "I", where the number 1 and 2 construct an increasing relationship.
Copied!
Example 2:
1
Input: "DI"
2
3
Output: [2,1,3]
4
5
Explanation:
6
Both [2,1,3] and [3,1,2] can construct the secret signature "DI",
7
but since we want to find the one with the smallest lexicographical permutation, you need to output [2,1,3]
Copied!

2. Implementation

(1) Two Pointers
思路:
假设 input String = "DDID"
1
原数组为 1 2 3 4 5
2
3
变换后得 3 2 1 5 4
Copied!
通过观察例子我们可以看到,string的[0,1]上有两个D,而对应的数组[0, 2]的数字被reversed. 同样,string在[3]上有D,而nums对应的位置[3,4]的数字也reversed,所以当D在string[i, j], i <= j出现时, 对应的nums数组在[i, j + 1]的数字要reverse
1
class Solution {
2
public int[] findPermutation(String s) {
3
int n = s.length();
4
5
int[] res = new int[n + 1];
6
7
for (int i = 0; i <= n; i++) {
8
res[i] = i + 1;
9
}
10
11
int i = 0;
12
while (i < n) {
13
if (s.charAt(i) == 'D') {
14
int j = i;
15
16
while (j < n && s.charAt(j) == 'D') {
17
++j;
18
}
19
reverse(res, i, j);
20
i = j;
21
}
22
++i;
23
}
24
return res;
25
}
26
27
public void reverse(int[] nums, int i, int j) {
28
while (i < j) {
29
int temp = nums[i];
30
nums[i] = nums[j];
31
nums[j] = temp;
32
++i;
33
--j;
34
}
35
}
36
}
Copied!
(2) Stack:
思路和上一种做法类似,只不过我们是通过stack达到reverse的效果。注意在最后我们要在stack加上s.length() + 1这个数
1
class Solution {
2
public int[] findPermutation(String s) {
3
int n = s.length();
4
int[] res = new int[n + 1];
5
6
Stack<Integer> stack = new Stack<>();
7
int j = 0;
8
for (int i = 1; i <= n; i++) {
9
if (s.charAt(i - 1) == 'D') {
10
stack.push(i);
11
}
12
else {
13
stack.push(i);
14
while (!stack.isEmpty()) {
15
res[j] = stack.pop();
16
++j;
17
}
18
}
19
}
20
stack.push(n + 1);
21
while (!stack.isEmpty()) {
22
res[j] = stack.pop();
23
++j;
24
}
25
return res;
26
}
27
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)
Stack: 时间复杂度O(n), 空间复杂度O(n)