由范围 [0,n]
内所有整数组成的 n + 1
个整数的排列序列可以表示为长度为 n
的字符串 s
,其中:
- 如果
perm[i] < perm[i + 1]
,那么s[i] == 'I'
- 如果
perm[i] > perm[i + 1]
,那么s[i] == 'D'
给定一个字符串 s
,重构排列 perm
并返回它。如果有多个有效排列perm,则返回其中 任何一个 。
示例 1:
输入:s = "IDID" 输出:[0,4,1,3,2]
示例 2:
输入:s = "III" 输出:[0,1,2,3]
示例 3:
输入:s = "DDI" 输出:[3,2,0,1]
提示:
1 <= s.length <= 105
s
只包含字符"I"
或"D"
类似贪心思想,如果当前字母是 I
,我们只需要选择当前可选的最小数字,就能保证后面的数字无论怎么排列,当前数字和下一个数字一定是递增关系。D
同理,选择当前可选的最大数字即可
class Solution:
def diStringMatch(self, s: str) -> List[int]:
n = len(s)
low, high = 0, n
ans = []
for i in range(n):
if s[i] == 'I':
ans.append(low)
low += 1
else:
ans.append(high)
high -= 1
ans.append(low)
return ans
class Solution {
public int[] diStringMatch(String s) {
int n = s.length();
int low = 0, high = n;
int[] ans = new int[n + 1];
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'I') {
ans[i] = low++;
} else {
ans[i] = high--;
}
}
ans[n] = low;
return ans;
}
}
class Solution {
public:
vector<int> diStringMatch(string s) {
int n = s.size();
int low = 0, high = n;
vector<int> ans(n + 1);
for (int i = 0; i < n; ++i) {
if (s[i] == 'I') {
ans[i] = low++;
} else {
ans[i] = high--;
}
}
ans[n] = low;
return ans;
}
};
func diStringMatch(s string) []int {
n := len(s)
low, high := 0, n
var ans []int
for i := 0; i < n; i++ {
if s[i] == 'I' {
ans = append(ans, low)
low++
} else {
ans = append(ans, high)
high--
}
}
ans = append(ans, low)
return ans
}
function diStringMatch(s: string): number[] {
const n = s.length;
const res = new Array(n + 1);
let low = 0;
let high = n;
for (let i = 0; i < n; i++) {
if (s[i] === 'I') {
res[i] = low++;
} else {
res[i] = high--;
}
}
res[n] = low;
return res;
}
impl Solution {
pub fn di_string_match(s: String) -> Vec<i32> {
let s = s.as_bytes();
let n = s.len();
let mut res = Vec::with_capacity(n + 1);
let (mut low, mut high) = (-1, (n + 1) as i32);
for i in 0..n {
res.push(if s[i] == b'I' {
low += 1;
low
} else {
high -= 1;
high
});
}
res.push(low + 1);
res
}
}