LeetCode-DI String Match

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/84202677

Description:
Given a string S that only contains “I” (increase) or “D” (decrease), let N = S.length.

Return any permutation A of [0, 1, …, N] such that for all i = 0, …, N-1:

If S[i] == "I", then A[i] < A[i+1]
If S[i] == "D", then A[i] > A[i+1]

Example 1:

Input: "IDID"
Output: [0,4,1,3,2]

Example 2:

Input: "III"
Output: [0,1,2,3]

Example 3:

Input: "DDI"
Output: [3,2,0,1]

Note:

  • 1 <= S.length <= 10000
  • S only contains characters “I” or “D”.

题意:根据给定的字符串S(仅包含字符’I’和’D’),返回一个包含元素[0,N]的数组A(N是字符串的长度);要求数组中下标i处的元素,满足A[i] < A[i+1](如果Si处的字符为‘I’)或者A[i] > A[i+1](如果Si处的字符为‘D’);

解法:满足条件的结果有很多,只需要找到一个符合条件的元素排列即可;假设我们默认数组中的元素是递增排列的,那么此时影响结果的就是S中的字符‘D’,只需要解决字符‘D’对应数组下标位置处的元素,令其符合条件即可;我们可以这么做:首先遍历字符串S,每碰到一个字符‘D’时,将当前可分配的元素中的最大值赋予数组对应位置处,这样遍历完字符串S后,我们得到的数组就已经解决了字符‘D’的问题,这时候,只需要遍历数组将其没有赋值的位置,按照剩余可分配元素从小到大的顺序依次填充即可;

Java
class Solution {
    public int[] diStringMatch(String S) {
        int[] result = new int[S.length() + 1];
        ArrayDeque<Integer> digit = new ArrayDeque<>();
        for (int i = 0; i < result.length; i++) digit.addLast(i);
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == 'D') result[i] = digit.removeLast();
            else result[i] = -1;
        }
        for (int i = 0; i < result.length; i++) {
            result[i] = result[i] == -1 ? digit.removeFirst() : result[i];
        }
        result[S.length()] = digit.removeFirst();
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/84202677