g0901_1000.s0942_di_string_match.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0901_1000.s0942_di_string_match;
// #Easy #Array #String #Math #Greedy #Two_Pointers
// #2022_03_30_Time_4_ms_(33.74%)_Space_48.7_MB_(20.18%)
/**
* 942 - DI String Match\.
*
* Easy
*
* A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:
*
* * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* * `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
*
* Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**.
*
* **Example 1:**
*
* **Input:** s = "IDID"
*
* **Output:** [0,4,1,3,2]
*
* **Example 2:**
*
* **Input:** s = "III"
*
* **Output:** [0,1,2,3]
*
* **Example 3:**
*
* **Input:** s = "DDI"
*
* **Output:** [3,2,0,1]
*
* **Constraints:**
*
* * 1 <= s.length <= 105
* * `s[i]` is either `'I'` or `'D'`.
**/
public class Solution {
public int[] diStringMatch(String s) {
int[] arr = new int[s.length() + 1];
int max = s.length();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'D') {
arr[i] = max;
max--;
}
}
for (int i = s.length() - 1; i >= 0 && max > 0; i--) {
if (s.charAt(i) == 'I' && arr[i + 1] == 0) {
arr[i + 1] = max;
max--;
}
}
for (int i = 0; i < arr.length && max > 0; i++) {
if (arr[i] == 0) {
arr[i] = max;
max--;
}
}
return arr;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy