[Leetcode][Easy] 942. DI String Match

    xiaoxiao2023-10-20  178

    文章目录

    ProblemAnswerExplanation

    Problem

    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]

    Answer

    vector<int> diStringMatch(string S) { int left = 0, right = S.size(); vector<int> res; for (char &c : S) res.push_back(c == 'I' ? left++ : right--); res.push_back(left); return res; }

    Explanation

    Highest vote answer is not easy to understand. So I wrote my own. When the char is I, current number should be larger than the next one and when the char is D, should be smaller than the next one. So actually, it is increasing and decresing. We set highest as the size of S and start from 0. when the for loop finishes, we put the last one into res

    最新回复(0)