leetcode-942-easy

DI String Match

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'.

思路一:先向前遍历字符串,找 D 的位置,n 依次减一,然后设置值,最后向后遍历字符串,找 I 的位置, n 同样依次减一

    public static int[] diStringMatch(String s) {
        int[] result = new int[s.length() + 1];

        char[] chars = s.toCharArray();

        int n = s.length();

        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == 'D') {
                result[i] = n--;
            }
        }
        result[result.length - 1] = n--;

        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == 'I') {
                result[i] = n--;
            }
        }

        return result;
    }

思路二:看了一下官方的题解,思路更好,定义 low 和 high,直接遍历,遇到 I, low++,遇到 D, high--

posted @ 2023-01-13 21:52  iyiluo  阅读(21)  评论(0)    收藏  举报