Input: s ="I"Output: [1,2]Explanation: [1,2]is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
Example 2:
1
2
3
Input: s ="DI"Output: [2,1,3]Explanation: Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return[2,1,3]
To get the lexicographically smallest permutation, we process the string from left to right, pushing numbers onto a stack. When we see an ‘I’ or reach the end, we pop all elements from the stack to the answer. This reverses the order for ‘D’ runs, ensuring the smallest permutation.
classSolution {
public: vector<int> findPermutation(string s) {
vector<int> ans, stk;
int n = s.size();
for (int i =0; i <= n; ++i) {
stk.push_back(i+1);
if (i == n || s[i] =='I') {
while (!stk.empty()) {
ans.push_back(stk.back());
stk.pop_back();
}
}
}
return ans;
}
};
classSolution {
publicint[]findPermutation(String s) {
int n = s.length();
int[] ans =newint[n+1];
Deque<Integer> stk =new ArrayDeque<>();
int idx = 0;
for (int i = 0; i <= n; i++) {
stk.push(i+1);
if (i == n || s.charAt(i) =='I') {
while (!stk.isEmpty()) ans[idx++]= stk.pop();
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funfindPermutation(s: String): IntArray {
val n = s.length
val ans = mutableListOf<Int>()
val stk = ArrayDeque<Int>()
for (i in0..n) {
stk.addLast(i+1)
if (i == n || s[i] =='I') {
while (stk.isNotEmpty()) ans.add(stk.removeLast())
}
}
return ans.toIntArray()
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deffindPermutation(self, s: str) -> list[int]:
ans, stk = [], []
n = len(s)
for i in range(n+1):
stk.append(i+1)
if i == n or s[i] =='I':
while stk:
ans.append(stk.pop())
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnfind_permutation(s: String) -> Vec<i32> {
let n = s.len();
letmut ans = Vec::new();
letmut stk = Vec::new();
for i in0..=n {
stk.push((i+1) asi32);
if i == n || s.as_bytes()[i] ==b'I' {
whilelet Some(x) = stk.pop() {
ans.push(x);
}
}
}
ans
}
}